JSON: JsonMappingException while try to deserialize object with null values

VB_ picture VB_ · Aug 7, 2013 · Viewed 80.5k times · Source

I try to deserialize object that contains null-properties and have the JsonMappingException.

What I do:

String actual = "{\"@class\" : \"PersonResponse\"," +
                "  \"id\" : \"PersonResponse\"," +
                "  \"result\" : \"Ok\"," +
                "  \"message\" : \"Send new person object to the client\"," +
                "  \"person\" : {" +
                "    \"id\" : 51," +
                "    \"firstName\" : null}}";
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(new StringReader(json), PersonResponse.class); //EXCEPTION!

BUT: if to throw away "firstName = null" property - all works fine! I mean pass the next string:

String test = "{\"@class\" : \"PersonResponse\"," +
                "  \"id\" : \"PersonResponse\"," +
                "  \"result\" : \"Ok\"," +
                "  \"message\" : \"Send new person object to the client\"," +
                "  \"person\" : {" +
                "    \"id\" : 51}}";
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(new StringReader(json), PersonResponse.class); //ALL WORKS FINE!

Question: How to avoid this exception or to pledge Jackson ignore null-values during serialization?

Throws:

Message:

com.fasterxml.jackson.databind.MessageJsonException:
 com.fasterxml.jackson.databind.JsonMappingException:
  N/A (through reference chain: person.Create["person"]->Person["firstName"])

cause:

com.fasterxml.jackson.databind.MessageJsonException:
 com.fasterxml.jackson.databind.JsonMappingException:
  N/A (through reference chain: prson.Create["person"]->Person["firstName"])

cause: java.lang.NullPointerException

Answer

Neman picture Neman · Jun 4, 2015

Sometimes this problem occurs when accidentally using a primitive type as return type of the getter of a non-primitive field:

public class Item
{
    private Float value;

    public float getValue()
    {
        return value;
    }

    public void setValue(Float value)
    {
        this.value = value;
    }   
}

Notice the "float" instead of "Float" for the getValue()-method, this can lead to a Null Pointer Exception, even when you have added

objectMapper.setSerializationInclusion(Include.NON_NULL);