ObjectMapper截断Map中的日期

时间:2019-03-20 17:07:30

标签: java serialization java-time objectmapper

我有一个ObjectMapper,配置了以下DateTimeFormatter

DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").withZone(ZoneOffset.UTC);

我想将其中带有OffsetDateTime的地图转换为json。我的问题是,OffsetDateTime显然是正确转换的值

Map<Integer, OffsetDateTime> map = ImmutableMap.of(1, offsetDateTime);
System.out.println(mapper.writeValueAsString(map));
// {"1":"2019-03-20T16:46:00.000+0000"}

但不是关键的时候

Map<OffsetDateTime, Integer> map = ImmutableMap.of(offsetDateTime, 1);
System.out.println(mapper.writeValueAsString(map).toString());
// {"2019-03-20T16:46Z":1}

请注意,秒和毫秒已被截断。我已经使用其他地图(例如HashMapTreeMap)对此进行了测试,结果相同。

这是ObjectMapper的定义:

ObjectMapper mapper = new ObjectMapper();

mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.setDateFormat(DateConstants.SIMPLE_DATE_FORMATTER);
mapper.registerModule(new JavaTimeModule());

SimpleModule instantModule = new SimpleModule();
instantModule.addDeserializer(OffsetDateTime.class, new OffsetDateTimeDeserializer());
instantModule.addSerializer(OffsetDateTime.class, new OffsetDateTimeSerializer());

mapper.registerModule(instantModule);
mapper.registerModule(offsetDateTimeModule);

和此序列化器:

public class OffsetDateTimeSerializer extends JsonSerializer<OffsetDateTime> {
    @Override
    public void serialize(OffsetDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        String str = DateConstants.FORMATTER.format(value);
        gen.writeString(str);
    }
}

在合并后答案后进行编辑:

我现在将SimpleModule更改为

SimpleModule instantModule = new SimpleModule();
instantModule.addDeserializer(OffsetDateTime.class, new OffsetDateTimeDeserializer());
instantModule.addKeyDeserializer(OffsetDateTime.class, new OffsetDateTimeKeyDeserializer());
instantModule.addSerializer(OffsetDateTime.class, new OffsetDateTimeSerializer());
instantModule.addKeySerializer(OffsetDateTime.class, new OffsetDateTimeSerializer());
mapper.registerModule(instantModule);

OffsetDateTimeKeyDeserialzer

public class OffsetDateTimeKeyDeserializer extends KeyDeserializer {
    @Override
    public OffsetDateTime deserializeKey(String key, DeserializationContext ctxt) {
        return OffsetDateTime.from(DateConstants.FORMATTER.parse(key));
    }
}

OffsetDateTime为值时,情况将继续正常运行。但是,如果这是关键,我现在会得到

Exception in thread "main" com.fasterxml.jackson.core.JsonGenerationException: Can not write a string, expecting field name (context: Object)
    at com.fasterxml.jackson.core.JsonGenerator._reportError(JsonGenerator.java:1961)
    at com.fasterxml.jackson.core.json.JsonGeneratorImpl._reportCantWriteValueExpectName(JsonGeneratorImpl.java:244)
    at com.fasterxml.jackson.core.json.WriterBasedJsonGenerator._verifyValueWrite(WriterBasedJsonGenerator.java:866)
    at com.fasterxml.jackson.core.json.WriterBasedJsonGenerator.writeString(WriterBasedJsonGenerator.java:368)
    at com.brandwatch.signals.commons.util.jackson.OffsetDateTimeSerializer.serialize(OffsetDateTimeSerializer.java:16)
    at com.brandwatch.signals.commons.util.jackson.OffsetDateTimeSerializer.serialize(OffsetDateTimeSerializer.java:12)
    at com.fasterxml.jackson.databind.ser.std.StdKeySerializers$Dynamic.serialize(StdKeySerializers.java:225)
    at com.fasterxml.jackson.databind.ser.std.MapSerializer.serializeFields(MapSerializer.java:707)
    at com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:639)
    at com.fasterxml.jackson.databind.ser.std.MapSerializer.serialize(MapSerializer.java:33)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider._serialize(DefaultSerializerProvider.java:480)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:319)
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3905)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3219)

编辑2:

这个KeySerializer似乎帮了我大忙:

public class OffsetDateTimeKeySerializer extends StdSerializer<Object> {

    public OffsetDateTimeKeySerializer() {
        super(Object.class);
    }

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        if (value instanceof OffsetDateTime) {
            String str = DateConstants.FORMATTER.format((OffsetDateTime) value);
            gen.writeFieldName(str);
        } else {
            gen.writeFieldName(value.toString());
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您已经发现,这仅将(反)序列化器应用于值。要将相同的序列化规则应用于密钥,您需要一个密钥(反序列化器):

instantModule.addKeyDeserializer(OffsetDateTime.class, new OffsetDateTimeDeserializer());
instantModule.addKeySerializer(OffsetDateTime.class, new OffsetDateTimeSerializer());

请注意,密钥反序列化器需要一个KeyDeserializer对象,而不是JsonDeserializer

the javadoc中的更多信息。