Maksim Sirotkin
Maksim Sirotkin

Reputation: 473

Java Spring Boot apply configuration for FasterXml Jackson library

I have Spring Boot project with Maven dependency: com.fasterxml.jackson.datatype

And I want to enable two properties ACCEPT_EMPTY_STRING_AS_NULL_OBJECT and FAIL_ON_READING_DUP_TREE_KEY.

But fail two enable them in two different ways: 1) application.yml

  jackson:
         serialization:
             WRITE_DATES_AS_TIMESTAMPS: false
         deserialization:
              FAIL_ON_READING_DUP_TREE_KEY: true

2) Adding them as Configuration 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 );
    }
}

Neither one of this ways gave me desired effect. Could you please advice correct way how to do it?

Upvotes: 2

Views: 11752

Answers (2)

Maksim Sirotkin
Maksim Sirotkin

Reputation: 473

I tried to use two options for FasterXml Jackson:

  1. ACCEPT_EMPTY_STRING_AS_NULL_OBJECT to automatically map empty strings to null values. And look like it is not working jet properly, according to https://github.com/FasterXML/jackson-databind/issues/1563 So I solved problem with writing custom deserialiser.
  2. FAIL_ON_READING_D‌​UP_TREE_KEY to enable Strict JSON validation, but the desired effect I get with JsonParser.Feature.STRICT_DUPLICATE_DETECTION.

So now I end up with two working solutions:

 @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;
    }

and application.yml

jackson:
     serialization:
         WRITE_DATES_AS_TIMESTAMPS: false
     parser:
          STRICT_DUPLICATE_DETECTION: true

I will use application.yml, of course, to keep configuration compact and in one place.

Thanks to @Michal Foksa I will accept your answer, because it is one of the ways how to configure ObjectMapper properly.

Upvotes: 5

Michal Foksa
Michal Foksa

Reputation: 12024

Create and configure ObjectMapper from scratch:

@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 );
    }
}

Upvotes: 3

Related Questions