use*_*356 9 java jackson java-time
我得到了以下代码:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String now = new ObjectMapper().writeValueAsString(new SomeClass(LocalDateTime.now()));
System.out.println(now);
Run Code Online (Sandbox Code Playgroud)
我得到了这个:
{ "时间":{ "小时":20, "分钟":49, "第二":42, "纳米":99000000, "DAYOFYEAR":19 "一周中的某天": "星期四", "月":"JANUARY ", "请将dayOfMonth":19, "年":2017年, "monthValue":1, "年表":{ "ID": "ISO", "calendarType": "ISO8601"}}}
我想要实现的是ISO8601中的字符串
2017-01-19T18:36:51Z
小智 20
这可能是由于您的代码中的错误.您正在使用新的未配置的mapper实例,这是修复:
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
String now = mapper.writeValueAsString(new SomeClass(LocalDateTime.now()));
System.out.println(now);
Run Code Online (Sandbox Code Playgroud)
我使用的SimpleModule最佳实践是拥有自己的序列化和反序列化注册实现:
final SimpleModule localDateTimeSerialization = new SimpleModule();
localDateTimeSerialization.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
localDateTimeSerialization.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
objectMapper.registerModule(localDateTimeSerialization);
Run Code Online (Sandbox Code Playgroud)
序列化器:
public class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
private final DateTimeFormatter format = DateTimeFormatter.ISO_DATE_TIME;
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString(value.format(format));
}
}
Run Code Online (Sandbox Code Playgroud)
和反序列化:
public class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
private final DateTimeFormatter fmt = DateTimeFormatter.ISO_DATE_TIME;
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext context) throws IOException {
return LocalDateTime.parse(p.getValueAsString(), fmt);
}
}
Run Code Online (Sandbox Code Playgroud)
这是你可以做的OffsetDateTime:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "uuuu-MM-dd'T'HH:mm:ss.SSSXXXX")
private OffsetDateTime timeOfBirth;
Run Code Online (Sandbox Code Playgroud)
对于 LocalDateTime,您不能使用 XXXX(区域偏移量),因为没有偏移量信息。所以你可以放弃它。但ISO8601 不鼓励使用当地时间,因为它不明确:
如果没有给出带有时间表示的 UTC 关系信息,则假定时间为当地时间。虽然在同一时区进行通信时假设当地时间可能是安全的,但在跨不同时区进行通信时使用本地时间是不明确的。即使在单个地理时区内,如果该地区实行夏令时,某些当地时间也会不明确。通常 最好使用标准的符号来指示时区(区域指示符)。
| 归档时间: |
|
| 查看次数: |
12847 次 |
| 最近记录: |