我找到了如何自定义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;
}
最佳答案
您可以使用自定义序列化程序并在单个序列化程序中处理不同的格式。以下页面提供了有关如何创建自定义序列化器/反序列化器的一些信息:
-- 编辑--
来自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.
This means that you do not even need to call setObjectMapper
if you have Serializers/Deserializers defined by annotations (as described in the links I posted above). For your benefit, here is an example:
For Serializing:
Create a StdSerializer object to handle the type you are interested in
public class ItemSerializer extends StdSerializer<Item> {
// ...
@Override
public void serialize(Item value, JsonGenerator jgen, SerializerProvider provider) {
// Write the Item data into the JsonGenerator
}
}
通过注释为对象定义序列化器
@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 {
// ...
}
关于java - 自定义和不同的 json 日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44403172/