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
Enable Object Mapper writeValueAsString method to include null values
提问by LINGS
I have a JSON object which may contain a few null
values.
I use ObjectMapper
from com.fasterxml.Hymanson.databind
to convert my JSON object as String
.
我有一个 JSON 对象,它可能包含一些null
值。我使用ObjectMapper
fromcom.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 String
that comes from writeValueAsString()
.
I want my ObjectMapper
to give me all fields in the String
even 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 null
fields to null
by 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.ALWAYS
worked 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 Include
are:
其他可能的值为Include
:
Include.NON_DEFAULT
Include.NON_EMPTY
Include.NON_NULL
Include.NON_DEFAULT
Include.NON_EMPTY
Include.NON_NULL