give a default value for an attribute if the value is null in json by jackson

Suppose i have class ie

private class Student {
        private Integer x = 1000;

        public Integer getX() {
            return x;
        }

        public void setX(Integer x) {
            this.x = x;
        }
    }

Now suppose json is "{x:12}" and doing deserialization then the x will have the value is 12 . But if the json is "{}" then the value of x = 1000 (get is from the default value of the attribute declared in the class).

Now if the json is "{x:null}" then value of x becomes null but here even in this case i want value of x to be 1000 . How to do it via jackson . Thanks in advance.

I am deserializing via below method, if it helps in anyway: objectMapper.readValue(<json string goes here>, Student.class);


You should be able to override the setter. Add the @JsonProperty(value="x") annotations to the getter and setter to let Jackson know to use them:

private class Student {
    private static final Integer DEFAULT_X = 1000;
    private Integer x = DEFAULT_X;

    @JsonProperty(value="x")
    public Integer getX() {
        return x;
    }

    @JsonProperty(value="x")
    public void setX(Integer x) {
        this.x = x == null ? DEFAULT_X : x;
    }
}

Consider extending JsonDeserializer

custom deserializer:

public class StudentDeserializer extends JsonDeserializer<Student> {
    @Override
    public Student deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        JsonNode node = p.getCodec().readTree(p);
        // if JSON is "{}" or "{"x":null}" then create Student with default X
        if (node == null || node.get("x").isNull()) {
            return new Student();
        }
        // otherwise create Student with a parsed X value
        int x = (Integer) ((IntNode) node.get("x")).numberValue();
        Student student = new Student();
        student.setX(x);
        return student;
    }
}

and it's use:

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Student.class, new StudentDeserializer());
mapper.registerModule(module);     
Student readValue = mapper.readValue(<your json string goes here>", Student.class);

从json到object,你可以在setter中解决这个问题,并告诉Jackson不要使用Field访问,而是使用setter来解组。

链接地址: http://www.djcxy.com/p/84270.html

上一篇: 如何在我的网站服务器上运行node.js而不是我的电脑本地服务器

下一篇: 如果json by jackson中的值为null,则为该属性提供默认值