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

标签 java json string serialization jackson

我有一个 JSON 对象,其中可能包含一些 null值。 我用 ObjectMapper来自 com.fasterxml.jackson.databind将我的 JSON 对象转换为 String .

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

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

例子:

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

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

最佳答案

Jackson 应该默认将 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;
        }
    }
}

打印

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

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

关于java - 启用对象映射器 writeValueAsString 方法以包含空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23297402/

相关文章:

java - 命令([var] 类型)的作用是什么?

java - 我的列表中的 Grails .size().toString() 不起作用

java - Jersey 休息 api 安全

JAVA Swing : Can't add text area to a Border Layout

java - org.springframework.web.bind.MissingServletRequestParameterException异常

javascript - 使用 Lodash 转换这个嵌套的 json 数据

r - 提取短语前的数字

javascript - 使用js删除localstorage中的json对象

php - 如何在PHP中查找以 ','分隔的字符串

c++ - 将整数转换为 ascii 值 C++