0

I am using jackson 2.6.3 to do the JSON marshal/unmarshal. If a field is missing from the payload, then the setter of the field is not called. I need to plugin some default values if the field is missing from payload. Also some business logic check. Not sure where to put it if not in the setter. Using Spring boot 1.4.0.

any hints/clues are deeply appreciated

gigi2
  • 1,996
  • 1
  • 17
  • 22
  • Possible duplicate of [Setting default values to null fields when mapping with Jackson](http://stackoverflow.com/questions/18805455/setting-default-values-to-null-fields-when-mapping-with-jackson) – Henrik Aasted Sørensen Feb 10 '17 at 08:51

2 Answers2

0

You can use parameterized constructor with @JsonCreator on constructor and @JsonProperty in constructor parameters. Then Jackson will always call this constructor to deserialize even if any attribute is null. You can set default value there if any value is null or even you can do business logic checks.

Sample:

public class Person {
    private Integer id;
    private String name;

    @JsonCreator
    public Person(@JsonProperty(value = "id") Integer id, @JsonProperty(value = "name") String name) {
        this.id = id != null ? id : Integer.valueOf(1); //setting default
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
Monzurul Shimul
  • 8,132
  • 2
  • 28
  • 42
0

You can use DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES to false.

If you need to override the spring boot automatic configuration by extending WebMvcConfigrationAdaptor class from Spring to add HttpMessageConverter, this configuration will ignore any unknown properties while deserialization.

 @Configuration
 class WebConfiguration extends WebMvcConfigurerAdapter{



    @Override
    public void configureMessageConverters(
            List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.indentOutput(true).dateFormat(
                new SimpleDateFormat("yyyy-MM-dd"));

        converters.add(new MappingJackson2HttpMessageConverter(builder.build()
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
                        false)));


    }
}

Hope this helps you.

Vipul Panth
  • 5,221
  • 4
  • 16
  • 27