当我们从pojo转换为json时,如何获得没有空字符串的结果json?
class Test{
public String id;
public String firstname;
public String lastname;
}
Test test=new Test();
test.id="1";
test.firstname="John";
当我们将测试转换为json时:
Json.tojson(test); // using play.libs.Json
结果:
{
"id":"1",
"firstname":"John",
"lastname":null
}
预期结果:
{
"id":"1",
"firstname":"John"
}
有人可以帮忙吗?谢谢。
答案 0 :(得分:1)
您应该注释您的POJO,例如:
/**
* Test class annotate to tell Jackson library to NOT include NULL values.
*/
@JsonInclude(Include.NON_NULL)
class Test {
public String id;
public String firstname;
public String lastname;
}
答案 1 :(得分:0)
要禁止使用空值序列化属性,可以直接配置ObjectMapper,或者使用@JsonInclude批注:
mapper.setSerializationInclusion(Include.NON_NULL);
或:
@JsonInclude(Include.NON_NULL)
class Foo
{
String bar;
}