java 如果 jackson 在 json 中的值为 null,则为属性提供默认值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29176325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:48:38  来源:igfitidea点击:

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

javajsonHymanson

提问by Trying

Suppose i have class i.e.

假设我有课,即

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 xwill 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).

现在假设 json is"{x:12}"并进行反序列化,那么它x的值为12. 但是,如果JSON是 "{}"那么的值x = 1000(get是从类中声明的属性的默认值)。

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

现在,如果 json 是 "{x:null}"x 的值,null但即使在这种情况下,我也希望值x1000如何通过 Hymanson 做到这一点。提前致谢。

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

我正在通过以下方法反序列化,如果它有帮助的话: objectMapper.readValue(<json string goes here>, Student.class);

采纳答案by Trying

public class Student {
    private Integer x = Integer.valueOf(1000);

    public Integer getX() {
        return x;
    }

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

This works for me........

这对我有用......

Test code 1:

测试代码1:

public static void main(String[] args) throws IOException {
        String s = "{\"x\":null}";
        ObjectMapper mapper = new ObjectMapper();
        Student ss = mapper.readValue(s, Student.class);
        System.out.println(ss.getX());
    }

output:

输出:

1000

1000

Test code 2:

测试代码2:

public static void main(String[] args) throws IOException {
        String s = "{}";
        ObjectMapper mapper = new ObjectMapper();
        Student ss = mapper.readValue(s, Student.class);
        System.out.println(ss.getX());
    }

output:

输出:

1000

1000

回答by Steve K

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

您应该能够覆盖 setter。将@JsonProperty(value="x")注释添加到 getter 和 setter 以让 Hymanson 知道使用它们:

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

回答by Sergey Pauk

Consider extending JsonDeserializer

考虑扩展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);

回答by Stefaan Neyts

From json to object, you could fix this in the setter and tell Hymanson to not use Field access but use the setter for unmarshalling.

从 json 到对象,您可以在 setter 中修复此问题,并告诉 Hymanson 不要使用 Field 访问,而是使用 setter 进行解组。