Enable Jackson Deserialization of Empty Objects to Null

How to tell Jackson to ignore empty object during deserialization?

I would use a JsonDeserializer. Inspect the field in question, determine, if it is emtpy and return null, so your ContainedObject would be null.

Something like this (semi-pseudo):

 public class MyDes extends JsonDeserializer<ContainedObject> {

@Override
public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {
//read the JsonNode and determine if it is empty JSON object
//and if so return null

if (node is empty....) {
return null;
}
return node;
}

}

then in your model:

 public class Entity {
private long id;
private String description;

@JsonDeserialize(using = MyDes.class)
private ContainedObject containedObject;

//Contructor, getters and setters omitted

}

Hope this helps!

Why Doesn't Setting Jackson to Accept Empty Lists as Null Work?

For this example case, my problem was the @EnableWebMvc annotation within the ExampleApplication class. Removing that annotation allowed me to successfully send an empty array to my endpoint, which then received it as a null object.

Note

My original problem still exists within my company's application, even after removing the annotation. However, it seems like this may be an issue with a different setting that might be clashing with ...accept-empty-arrays-as-null-object.

Do not include empty object to Jackson

Without a custom serializer, jackson will include your object.

Solution 1 : Replace new object with null

person.setDetails(new PersonDetails());

with

person.setDetails(null);

and add

@JsonInclude(Include.NON_NULL)
public class Person {

Solution 2: Custom serializer

public class PersonDetailsSerializer extends StdSerializer<PersonDetails> {

public PersonDetailsSerializer() {
this(null);
}

public PersonDetailsSerializer(Class<PersonDetails> t) {
super(t);
}

@Override
public void serialize(
PersonDetails personDetails, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
// custom behavior if you implement equals and hashCode in your code
if(personDetails.equals(new PersonDetails()){
return;
}
super.serialize(personDetails,jgen,provider);
}
}

and in your PersonDetails

public class Person {
private String name;
@JsonSerialize(using = PersonDetailsSerializer.class)
private PersonDetails details;
}

Jackson Mapper - how to fail on null or empty values

There is an option called: FAIL_ON_NULL_FOR_CREATOR_PARAMETERS.

So I assume it would be accessible at: DeserializationConfig.Feature.FAIL_ON_NULL_FOR_CREATOR_PARAMETERS;

Or in yml:

jackson:
serialization:
indent-output: false
deserialization:
fail-on-unknown-properties: true
fail-on-missing-creator-properties: true
fail-on-null-creator-properties: true

This works on all types, strings, ints, doubles etc..



Related Topics



Leave a reply



Submit