Java 启用对象映射器 writeValueAsString 方法以包含空值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23297402/
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-08-13 21:44:17  来源:igfitidea点击:

Enable Object Mapper writeValueAsString method to include null values

javajsonstringserializationHymanson

提问by LINGS

I have a JSON object which may contain a few nullvalues. I use ObjectMapperfrom com.fasterxml.Hymanson.databindto convert my JSON object as String.

我有一个 JSON 对象,它可能包含一些null值。我使用ObjectMapperfromcom.fasterxml.Hymanson.databind将我的 JSON 对象转换为String.

private ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(object);

If my object contains any field that contains a value as null, then that field is not included in the Stringthat comes from writeValueAsString(). I want my ObjectMapperto give me all fields in the Stringeven if their value is null.

如果我的对象包含任何包含 as 值的null字段,则该字段不包含在String来自writeValueAsString(). 我希望我ObjectMapper给我所有字段,String即使它们的值是null.

Example:

例子:

object = {"name": "John", "id": 10}
json   = {"name": "John", "id": 10}

object = {"name": "John", "id": null}
json   = {"name": "John"}

回答by Sotirios Delimanolis

Hymanson should serialize nullfields to nullby default. See the following example

Hymanson 应该默认将null字段序列化为null。看下面的例子

public class Example {

    public static void main(String... args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        String json = mapper.writeValueAsString(new Test());
        System.out.println(json);
    }

    static class Test {
        private String help = "something";
        private String nope = null;

        public String getHelp() {
            return help;
        }

        public void setHelp(String help) {
            this.help = help;
        }

        public String getNope() {
            return nope;
        }

        public void setNope(String nope) {
            this.nope = nope;
        }
    }
}

prints

印刷

{
  "help" : "something",
  "nope" : null
}

You don't need to do anything special.

你不需要做任何特别的事情。

回答by Abbin Varghese

Include.ALWAYSworked for me. objectMapper.setSerializationInclusion(com.fasterxml.Hymanson.annotation.JsonInclude.Include.ALWAYS);

Include.ALWAYS为我工作。objectMapper.setSerializationInclusion(com.fasterxml.Hymanson.annotation.JsonInclude.Include.ALWAYS);

Other possible values for Includeare:

其他可能的值为Include

  • Include.NON_DEFAULT
  • Include.NON_EMPTY
  • Include.NON_NULL
  • Include.NON_DEFAULT
  • Include.NON_EMPTY
  • Include.NON_NULL