Jackson,java.time,ISO 8601,序列化无毫秒

时间:2016-11-08 13:02:46

标签: java jackson java-time jackson-modules jackson2

我使用的是Jackson 2.8,需要与ISO 8601时间戳内不允许毫秒的API进行通信。

预期格式为:"2016-12-24T00:00:00Z"

我使用Jackson的JavaTimeModule,WRITE_DATES_AS_TIMESTAMPS设置为false

但这会打印毫秒。

所以我尝试使用objectMapper.setDateFormat并没有改变任何内容。

我目前的解决方法是:

ObjectMapper om = new ObjectMapper();

DateTimeFormatter dtf = new DateTimeFormatterBuilder()
    .appendInstant(0)
    .toFormatter();

JavaTimeModule jtm = new JavaTimeModule();
jtm.addSerializer(Instant.class, new JsonSerializer<Instant>() {
    @Override
    public void serialize(Instant value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
        gen.writeString(dtf.format(value));
    }
});

om.registerModule(jtm);

我重写了Instant.class的默认序列化程序。

使用一些配置参数解决这个问题有什么好办法吗?

3 个答案:

答案 0 :(得分:5)

更新

只需在@JsonFormat属性上方添加日期格式的Instant注释即可。这很容易。

如果你有一个像JavaTimeModule的ObjectMapper,就像下一个:

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

如果您的类具有Instant属性,则应添加@JsonFormat注释并将日期模式设置为毫秒数。就像下一个:

public static class TestDate {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd hh:mm:ss", timezone = "UTC")
    Instant instant;

    //getters & setters
}

因此,如果将一个对象序列化为Json,它可以完美地运行:

String json = mapper.writeValueAsString(testDate);
System.out.println(json); 

<强>输出

  

{“instant”:“2016-11-10 06:03:06”}

旧答案。我不知道为什么,但它不起作用:

您可以使用Jackson2ObjectMapperBuilder来构建它。

您只需添加所需的dateFormat即可。这将是下一个:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

ObjectMapper mapper = Jackson2ObjectMapperBuilder
            .json()       
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) 
            .modules(new JavaTimeModule())
            .dateFormat(dateFormat)
            .build();

答案 1 :(得分:4)

这是一个可以全局设置的替代方法,但是需要使用ZonedDateTime和即时格式化器,因为我们无法设置Java Time Module随附的Instant Serializer的格式

您不会看到使用分区日期时间为即时的任何副作用,因为jackson分别序列化区域ID并默认禁用。从技术上讲,这类似于将格式化程序应用于Instant

以这种方式使用时,ZonedDateTime序列化程序会将序列化委派给InstantBaseSerializer并使用指定的自定义格式。

@RunWith(JUnit4.class)
public class InstantNoMillisTest {

    private ObjectMapper objectMapper;

    @Before
    public void init() {
        JavaTimeModule module = new JavaTimeModule();
        ZonedDateTimeSerializer zonedDateTimeSerializer = new ZonedDateTimeSerializer(new DateTimeFormatterBuilder().appendInstant(0).toFormatter());
        module.addSerializer(ZonedDateTime.class, zonedDateTimeSerializer);
        module.addDeserializer(ZonedDateTime.class, InstantDeserializer.ZONED_DATE_TIME);

        objectMapper = Jackson2ObjectMapperBuilder.json()
                .modules(module)
                .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
                .build();
    }

    @Test
    public void serialize() throws IOException {
        ZonedDateTime zonedDateTime = ZonedDateTime.now();
        String noMillis = objectMapper.writeValueAsString(zonedDateTime);
        System.out.print(noMillis);
    }

    @Test
    public void deserialize() throws IOException {
        String dateTime = "\"2017-10-26T12:54:59Z\"";
        ZonedDateTime noMillis = objectMapper.readValue(dateTime, ZonedDateTime.class);
        System.out.print(noMillis);
    }
}

答案 2 :(得分:0)

下面是格式化Instant字段的一些Kotlin代码,因此它们将不包含毫秒,您可以使用自定义日期格式程序

ObjectMapper().apply {
        val javaTimeModule = JavaTimeModule()
        javaTimeModule.addSerializer(Instant::class.java, Iso8601WithoutMillisInstantSerializer())
        registerModule(javaTimeModule)
        disable(WRITE_DATES_AS_TIMESTAMPS)
    }

private class Iso8601WithoutMillisInstantSerializer
        : InstantSerializer(InstantSerializer.INSTANCE, false, DateTimeFormatterBuilder().appendInstant(0).toFormatter())
相关问题