我有一个 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/