JSON: JsonMappingException while try to deserialize object with null values

前端 未结 4 2199
时光说笑
时光说笑 2020-12-05 10:04

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

What I do:

String actual =         


        
相关标签:
4条回答
  • 2020-12-05 11:02

    Add JsonProperty annotation to your attribute in TO class, as below

    @JsonProperty
    private String id;
    
    0 讨论(0)
  • 2020-12-05 11:03

    I also faced the same issue.

    I just included a default constructor in the model class along with the other constructor with parameters.

    It worked.

    package objmodel;
    
    import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
    import com.fasterxml.jackson.databind.annotation.JsonSerialize;
    
    public class CarModel {
    
    private String company;
    private String model;
    private String color;
    private String power;
    
    
    public CarModel() {
    }
    
    public CarModel(String company, String model, String color, String power) {
        this.company = company;
        this.model = model;
        this.color = color;
        this.power = power;
    
    }
    
    @JsonDeserialize
    public String getCompany() {
        return company;
    }
    
    public void setCompany(String company) {
        this.company = company;
    }
    
    @JsonDeserialize
    public String getModel() {
        return model;
    }
    
    public void setModel(String model) {
        this.model = model;
    }
    
    @JsonDeserialize
    public String getColor() {
        return color;
    }
    
    public void setColor(String color) {
        this.color = color;
    }
    
    @JsonDeserialize
    public String getPower() {
        return power;
    }
    
    public void setPower(String power) {
        this.power = power;
    }
    }
    
    0 讨论(0)
  • 2020-12-05 11:05

    If you don't want to serialize null values, you can use the following setting (during serialization):

    objectMapper.setSerializationInclusion(Include.NON_NULL);
    

    Hope this solves your problem.

    But the NullPointerException you get during deserialization seems suspicious to me (Jackson should ideally be able to handle null values in the serialized output). Could you post the code corresponding to the PersonResponse class?

    0 讨论(0)
  • 2020-12-05 11:10

    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);
    
    0 讨论(0)
提交回复
热议问题