Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
911 views
in Technique[技术] by (71.8m points)

java - JSON: JsonMappingException while try to deserialize object with null values

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...