我有Maven依赖的Spring Boot项目:com.fasterxml.jackson.datatype
我想启用两个属性ACCEPT_EMPTY_STRING_AS_NULL_OBJECT和FAIL_ON_READING_DUP_TREE_KEY。
但是失败的两个以两种不同的方式启用它们: 1)application.yml
jackson:
serialization:
WRITE_DATES_AS_TIMESTAMPS: false
deserialization:
FAIL_ON_READING_DUP_TREE_KEY: true
2)将它们添加为配置Bean
@Configuration
public class JacksonConfiguration {
@Autowired
private ObjectMapper objectMapper;
@PostConstruct
private void configureObjectMapper() {
objectMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT );
objectMapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY );
}
}
这两种方式都没有给我带来预期的效果。能否请您正确告知如何做到这一点?
答案 0 :(得分:2)
我试图为FasterXml Jackson使用两个选项:
所以现在我最终得到了两个有效的解决方案:
@Bean
public ObjectMapper objectMapper() {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
return objectMapper;
}
和application.yml
jackson:
serialization:
WRITE_DATES_AS_TIMESTAMPS: false
parser:
STRICT_DUPLICATE_DETECTION: true
我当然会使用application.yml来保持配置紧凑并在一个地方。
感谢@Michal Foksa我会接受你的回答,因为这是正确配置ObjectMapper的方法之一。
答案 1 :(得分:1)
从头开始创建和配置ObjectMapper
:
@Configuration
public class JacksonConfiguration {
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper()
.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT )
.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY );
}
}