json Jackson SerializationFeature.WRITE_DATES_AS_TIMESTAMPS 在春季不关闭时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27978762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Hymanson SerializationFeature.WRITE_DATES_AS_TIMESTAMPS not turning off timestamps in spring
提问by drekka
After a lot of searching I tracked down how to stop java.util.Date fields from being serialised into timestamps when converting to JSON responses in my @RestController.
经过大量搜索,我找到了在@RestController 中转换为 JSON 响应时如何阻止 java.util.Date 字段被序列化为时间戳的方法。
However I cannot get it to work. All the posts I found said to disable the SerializationFeature.WRITE_DATES_AS_TIMESTAMPS feature of the Hymanson objet mapper. So I wrote the following code:
但是我无法让它工作。我发现的所有帖子都说禁用了 Hymanson 对象映射器的 SerializationFeature.WRITE_DATES_AS_TIMESTAMPS 功能。所以我写了下面的代码:
public class MVCConfig {
@Autowired
Hymanson2ObjectMapperFactoryBean objectMapper;
@PostConstruct
public void postConstruct() {
this.objectMapper.setFeaturesToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
}
As I understand it, a config is a bean as well so auto wiring in the object mapper to set additional properties should work. I've used break points and everything looks good with this setup.
据我了解,配置也是一个 bean,因此对象映射器中的自动连接以设置其他属性应该可以工作。我使用了断点,这个设置看起来一切都很好。
However when I serialise a bean with a java.util.Date property in a response to a http query, I'm still getting a time stamp.
但是,当我使用 java.util.Date 属性序列化一个 bean 以响应 http 查询时,我仍然得到一个时间戳。
Does anyone know why this is not working? It's got me stumped !
有谁知道为什么这不起作用?它让我难住了!
回答by drekka
After lots of messing around I found that the following code fixed the problem:
经过大量的混乱,我发现以下代码解决了这个问题:
public class MVCConfig extends WebMvcConfigurerAdapter {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
for (HttpMessageConverter<?> converter : converters) {
if (converter instanceof MappingHymanson2HttpMessageConverter) {
MappingHymanson2HttpMessageConverter jsonMessageConverter = (MappingHymanson2HttpMessageConverter) converter;
ObjectMapper objectMapper = jsonMessageConverter.getObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
break;
}
}
}
}
I'm not sure if there is an easier way to access the Hymanson MVC message converter and configure it. But this is working for me.
我不确定是否有更简单的方法来访问 Hymanson MVC 消息转换器并对其进行配置。但这对我有用。
回答by WesternGun
Yes I agree with @Feyyaz: adding config to the properties/yml file is the way to config the default, contextual (de)serializer, when this is out of your control and only left to be manipulated by Spring context.
是的,我同意 @Feyyaz:将配置添加到属性/yml 文件是配置默认的上下文(反)序列化器的方法,当这超出您的控制并且只能由 Spring 上下文操作时。
See this part of Spring documentation for more details:
有关更多详细信息,请参阅 Spring 文档的这一部分:
Citation in case of original link removal:
在原始链接删除的情况下引用:
79.3 Customize the Hymanson ObjectMapper
Spring MVC (client and server side) uses
HttpMessageConvertersto negotiate content conversion in an HTTP exchange. If Hymanson is on the classpath, you already get the default converter(s) provided byHymanson2ObjectMapperBuilder, an instance of which is auto-configured for you. TheObjectMapper(orXmlMapperfor Hymanson XML converter) instance (created by default) has the following customized properties:
MapperFeature.DEFAULT_VIEW_INCLUSIONis disabledDeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIESis disabledSerializationFeature.WRITE_DATES_AS_TIMESTAMPSis disabledSpring Boot also has some features to make it easier to customize this behavior. You can configure the
ObjectMapperandXmlMapperinstances by using the environment. Hymanson provides an extensive suite of simple on/off features that can be used to configure various aspects of its processing. These features are described in six enums:| Enum | Property | Values | | - | - | - | |
com.fasterxml.Hymanson.databind.DeserializationFeature|spring.Hymanson.deserialization.<feature_name>|true,false| |com.fasterxml.Hymanson.core.JsonGenerator.Feature|spring.Hymanson.generator.<feature_name>|true,false| |com.fasterxml.Hymanson.databind.MapperFeature|spring.Hymanson.mapper.<feature_name>|true,false| |com.fasterxml.Hymanson.core.JsonParser.Feature|spring.Hymanson.parser.<feature_name>|true,false| |com.fasterxml.Hymanson.databind.SerializationFeature|spring.Hymanson.serialization.<feature_name>|true,false| |com.fasterxml.Hymanson.annotation.JsonInclude.Include|spring.Hymanson.default-property-inclusion|always,non_null,non_absent,non_default,non_empty|For example, to enable pretty print, set
spring.Hymanson.serialization.indent_output=true. Note that, thanks to the use of relaxed binding, the case ofindent_outputdoes not have to match the case of the corresponding enum constant, which isINDENT_OUTPUT. This environment-based configuration is applied to the auto-configuredHymanson2ObjectMapperBuilderbean and applies to any mappers created by using the builder, including the auto-configuredObjectMapperbean. The context'sHymanson2ObjectMapperBuildercan be customized by one or moreHymanson2ObjectMapperBuilderCustomizerbeans. Such customizer beans can be ordered (Boot's own customizer has an order of 0), letting additional customization be applied both before and after Boot's customization. Any beans of typecom.fasterxml.Hymanson.databind.Moduleare automatically registered with the auto-configuredHymanson2ObjectMapperBuilderand are applied to anyObjectMapperinstances that it creates. This provides a global mechanism for contributing custom modules when you add new features to your application. If you want to replace the defaultObjectMappercompletely, either define a@Beanof that type and mark it as@Primaryor, if you prefer the builder-based approach, define aHymanson2ObjectMapperBuilder@Bean. Note that, in either case, doing so disables all auto-configuration of theObjectMapper. If you provide any@Beansof typeMappingHymanson2HttpMessageConverter, they replace the default value in the MVC configuration. Also, a convenience bean of typeHttpMessageConvertersis provided (and is always available if you use the default MVC configuration). It has some useful methods to access the default and user-enhanced message converters. See the “Section 79.4, “Customize the @ResponseBody Rendering”” section and theWebMvcAutoConfigurationsource code for more details.
79.3 自定义 Hymanson ObjectMapper
Spring MVC(客户端和服务器端)用于
HttpMessageConverters在 HTTP 交换中协商内容转换。如果 Hymanson 在类路径上,您已经获得了由 提供的默认转换器Hymanson2ObjectMapperBuilder,它的一个实例是为您自动配置的。该ObjectMapper(或XmlMapper为Hyman逊XML转换器)实例(默认创建)具有以下定义的属性:
MapperFeature.DEFAULT_VIEW_INCLUSION被禁用DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES被禁用SerializationFeature.WRITE_DATES_AS_TIMESTAMPS被禁用Spring Boot 还具有一些功能,可以更轻松地自定义此行为。您可以 使用环境配置
ObjectMapper和XmlMapper实例。Hymanson 提供了一套广泛的简单开/关功能,可用于配置其处理的各个方面。这些功能在六个枚举中描述:| 枚举 | 物业 | 价值观 | | - | - | - | |
com.fasterxml.Hymanson.databind.DeserializationFeature|spring.Hymanson.deserialization.<feature_name>|true,false| |com.fasterxml.Hymanson.core.JsonGenerator.Feature|spring.Hymanson.generator.<feature_name>|true,false| |com.fasterxml.Hymanson.databind.MapperFeature|spring.Hymanson.mapper.<feature_name>|true,false| |com.fasterxml.Hymanson.core.JsonParser.Feature|spring.Hymanson.parser.<feature_name>|true,false| |com.fasterxml.Hymanson.databind.SerializationFeature|spring.Hymanson.serialization.<feature_name>|true,false| |com.fasterxml.Hymanson.annotation.JsonInclude.Include|spring.Hymanson.default-property-inclusion|always,non_null,non_absent,non_default,non_empty|例如,要启用漂亮打印,请设置
spring.Hymanson.serialization.indent_output=true. 请注意,由于使用了 轻松绑定,因此 的大小写indent_output不必与对应的枚举常量的大小写匹配,即INDENT_OUTPUT. 这种基于环境的配置应用于自动配置的Hymanson2ObjectMapperBuilderbean 并应用于使用构建器创建的任何映射器,包括自动配置的ObjectMapperbean。上下文Hymanson2ObjectMapperBuilder可以由一个或多个Hymanson2ObjectMapperBuilderCustomizerbean自定义 。可以订购此类定制器 bean(Boot 自己的定制器的 order 为 0),允许在 Boot 定制之前和之后应用额外的定制。任何类型的 beans 都会com.fasterxml.Hymanson.databind.Module自动注册到 auto-configuredHymanson2ObjectMapperBuilder并应用于任何ObjectMapper它创建的实例。当您向应用程序添加新功能时,这提供了用于贡献自定义模块的全局机制。如果要ObjectMapper完全替换默认值 ,请定义@Bean该类型的 a 并将其标记为,@Primary或者,如果您更喜欢基于构建器的方法,则定义一个Hymanson2ObjectMapperBuilder@Bean. 请注意,在任何一种情况下,这样做都会禁用ObjectMapper. 如果您提供任何@BeanstypeMappingHymanson2HttpMessageConverter,它们将替换 MVC 配置中的默认值。此外,HttpMessageConverters还提供了一个方便的 bean 类型 (如果您使用默认的 MVC 配置,则始终可用)。它有一些有用的方法来访问默认和用户增强的消息转换器。见“第 79.4 节,“自定义 @ResponseBody 渲染”部分和WebMvcAutoConfiguration源代码以获取更多详细信息。
(StackOverFlow markdown does not support tables syntax so it is malformatted. Copy-paste this part in Sublime Text and save as .mdto view, or check the original link.)
(StackOverFlow markdown 不支持表格语法,所以格式不正确。复制粘贴这部分到 Sublime Text 并另存为.md查看,或查看原始链接。)
Examples:
例子:
spring:
Hymanson:
default-property-inclusion: non_null # to exclude null in json serialization
serialization:
write-dates-as-timestamps: true # write milliseconds since epoch in the final json
Or:
或者:
spring.Hymanson.default-property-inclusion: non_null # to exclude null in json serialization
spring.Hymanson.serialization.write-dates-as-timestamps: true # write milliseconds since epoch in the final json
回答by T D
ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new JavaTimeModule())
.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
回答by Master Slave
Yes, to hook in and change the object mapper that the converter is using you should do something like
是的,要连接并更改转换器正在使用的对象映射器,您应该执行以下操作
public class CustomObjectMapper extends ObjectMapper {
public CustomObjectMapper() {
this.configure(com.fasterxml.Hymanson.databind.SerializationFeature.
WRITE_DATES_AS_TIMESTAMPS, false);
}
}
and inside your MVCConfig
在你的MVCConfig里面
@Bean
public ObjectMapper HymansonObjectMapper() {
return new CustomObjectMapper();
}
@Bean
public SerializationConfig serializationConfig() {
return HymansonObjectMapper().getSerializationConfig();
}

