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

新手上路,请多包涵

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

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

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

例子:

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

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

原文由 LINGS 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 984
1 个回答

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
}

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

原文由 Sotirios Delimanolis 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题