编程语言
首页 > 编程语言> > java – 如何将包含LocalDate字段的json转换为可反序列化的格式?

java – 如何将包含LocalDate字段的json转换为可反序列化的格式?

作者:互联网

我有一个存储在String中的对象.对象的一个​​字段是LocalDate.

"from": {
        "year": 1000,
        "month": "JANUARY",
        "era": "CE",
        "dayOfMonth": 1,
        "dayOfWeek": "WEDNESDAY",
        "dayOfYear": 1,
        "leapYear": false,
        "monthValue": 1,
        "chronology": {
            "calendarType": "iso8601",
            "id": "ISO"
        }
    }

我该如何将这个json转换为可用于反序列化的格式?

以下代码

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;


ObjectMapper om = new ObjectMapper();
om.registerModule(new JavaTimeModule());
MyCustomObject obj = om.readValue(json, MyCustomObject.class); //error

导致此异常:

com.fasterxml.jackson.databind.JsonMappingException: Unexpected token (START_OBJECT), expected VALUE_STRING: Expected array or string.

这是我用作MyCustomObject< LocalDate>的MyCustomObject类.

public class MyCustomObject<T> {
    private T from;
    private T to;

    public MyCustomObject() {
    }

    public T getFrom() {
        return this.from;
    }

    public void setFrom(T from) {
        this.from = from;
    }

    public T getTo() {
        return this.to;
    }

    public void setTo(T to) {
        this.to = to;
    }
}

解决方法:

LocalDate未正确存储在JSON中.

解决问题的正确方法是确保生成JSON的ObjectMapper已注册JavaTimeModuleJdk8Module.这可确保将LocalDate正确序列化为[年,月,日]的JSON数组.

蛮力方法是遵循@Roy在另一个答案中概述的解决方案,并手动将每个相关字段转换为LocalDate.有点像:

LocalDate date = LocalDate.now()
        .with(ChronoField.YEAR, year)
        .with(ChronoField.MONTH_OF_YEAR, Month.valueOf(month).getValue())
        .with(ChronoField.DAY_OF_MONTH, dayOfMonth);

这显然是容易出错的,而不是如何使用类.

标签:json,java,java-8,jackson,jsr310
来源: https://codeday.me/bug/20190705/1391527.html