Json 映射器将 LocalDate 转换为月份、年份、日期等

Json mapper converts LocalDate to month, year, day of month etc

Json 映射器将 LocalDate 转换为月、年、月中的某天...当将 java class 转换为 json 时,

"dob":{
  "year": 1992,
  "month": "MARCH",
  "dayOfMonth": 19,
  "dayOfWeek": "THURSDAY",
  "era": "CE",
  "dayOfYear": 79,
  "leapYear": true,
  "monthValue": 3,
  "chronology": {
    "calendarType": "iso8601",
    "id": "ISO"
  }
}

这在 mysql 中保存为 Date1992-03-19 如何 return 这个日期就像

"dob:1992-03-19"

杰克逊和 java.time 类型

Jackson JavaTimeModule is used to handle java.time序列化和反序列化。

它提供了一组 serializers and deserializers for the java.time types. If the SerializationFeature.WRITE_DATES_AS_TIMESTAMPS is disabled, java.time types will be serialized in standard ISO-8601 字符串表示。

以您的特定格式处理序列化

但是,一旦您拥有非常特殊的格式,您就可以创建自定义序列化程序:

public class DateOfBirthSerializer extends JsonSerializer<LocalDate> {

    @Override
    public void serialize(LocalDate value, JsonGenerator gen,
                          SerializerProvider serializers) throws IOException {
        gen.writeString("dob:" + value.format(DateTimeFormatter.ISO_DATE));
    }
}

那么就可以这样使用了:

public class Foo {

    @JsonSerialize(using = DateOfBirthSerializer.class)
    private LocalDate dateOfBirth;

    // Getters and setters
}

或者您可以使用:

SimpleModule module = new SimpleModule();
module.addSerializer(LocalDate.class, new DateOfBirthSerializer());

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);

它将应用于所有 LocalDate instances serialized with that ObjectMapper

以您的特定格式处理反序列化

对于反序列化,您可以使用类似的东西:

public class DateOfBirthDeserializer extends JsonDeserializer<LocalDate> {

    @Override
    public LocalDate deserialize(JsonParser p,
                                 DeserializationContext ctxt) throws IOException {

        String value = p.getValueAsString();
        if (value.startsWith("dob:")) {
            value = value.substring(4);
        } else {
            throw ctxt.weirdStringException(value, 
                    LocalDate.class, "Value doesn't start with \"dob:\"");
        }

        return LocalDate.parse(value, DateTimeFormatter.ISO_DATE);
    }
}