自定义和不同的json日期格式

时间:2017-06-07 03:50:57

标签: java json

我已经找到了如何自定义ObjectMapper日期格式,以便让Spring帮助自动序列化/反序列化(当我想将对象返回给客户端时序列化,当请求体是json对象时反序列化),但是我有很多具有不同日期格式的DTO,有些可能需要yyyy-mm-dd,有些是dd-mm-yyyy,有些ObjectMapper不适用于不同的所需日期格式,这是什么最佳实践解决方案问题

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    super.configureMessageConverters(converters);
    converters.add(mappingJacksonHttpMessageConverter());
}

MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter() {
    MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setDateFormat(new SimpleDateFormat("dd-MM-yyyy"));
    objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
    mappingJacksonHttpMessageConverter.setObjectMapper(objectMapper);
    mappingJacksonHttpMessageConverter.setPrettyPrint(true);
    return mappingJacksonHttpMessageConverter;
}

1 个答案:

答案 0 :(得分:1)

您可以使用自定义序列化程序并在单个序列化程序中处理不同的格式。以下是一些页面,其中包含有关如何创建自定义序列化程序/反序列化程序的一些信息:

Create Custom Serializer

Create Custom Deserializer

- 编辑 -

从Mapping documentation对于MappingJacksonHttpMessageConverter(添加了一些重点):

setObjectMapper
public void setObjectMapper(org.codehaus.jackson.map.ObjectMapper objectMapper)

    Set the ObjectMapper for this view. If not set, a default ObjectMapper is used.

    Setting a custom-configured ObjectMapper is one way to take further control
    of the JSON serialization process. For example, an extended SerializerFactory
    can be configured that provides custom serializers for specific types.
    The other option for refining the serialization process is to use Jackson's
    provided annotations on the types to be serialized, in which case a
    custom-configured ObjectMapper is unnecessary.

这意味着如果您有注释定义的序列化器/反序列化器(如我上面发布的链接中所述),您甚至不需要调用setObjectMapper。为了您的利益,这是一个例子:

用于序列化

创建一个StdSerializer对象来处理您感兴趣的类型

public class ItemSerializer extends StdSerializer<Item> {
    // ...

    @Override
    public void serialize(Item value, JsonGenerator jgen, SerializerProvider provider) {
        // Write the Item data into the JsonGenerator
    }
}

通过注释为对象定义Serializer

@JsonSerialize(using = ItemSerializer.class)
public class Item {
    // ...
}

反序列化

创建一个StdDeserializer对象来处理您感兴趣的类型

public class ItemDeserializer extends StdDeserializer<Item> { 
    // ... 

    @Override
    public Item deserialize(JsonParser jp, DeserializationContext ctxt) 
      throws IOException, JsonProcessingException {
        // Handle the different date formats here!

        return new Item(/*parsed date object*/);
    }
}

通过注释为对象定义反序列化器

@JsonDeserialize(using = ItemDeserializer.class)
public class Item {
    // ...
}