启用对象映射器写入值作为字符串方法以包含空值

2022-09-04 22:33:43

我有一个JSON对象,可能包含一些值。我使用 from 将我的 JSON 对象转换为 .nullObjectMappercom.fasterxml.jackson.databindString

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

如果我的对象包含任何包含值为 的字段,则该字段不包含在 来自 的 中。我希望我给我所有字段,即使他们的值为.nullStringwriteValueAsString()ObjectMapperStringnull

例:

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

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

答案 1

默认情况下,Jackson 应将字段序列化为。请参阅以下示例nullnull

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
}

您无需执行任何特殊操作。


答案 2

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

的其他可能值为:Include

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