模型类:
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AccountPojo implements Serializable {
@JsonView(JsonViews.AccountsPermissions.class)
private Integer id;
@JsonView(JsonViews.AccountsPermissions.class)
private String username;
@JsonView({JsonViews.AccountsPermissions.class,
JsonViews.AccountProfile.class})
private String firstName;
@JsonView({JsonViews.AccountsPermissions.class,JsonViews.AccountProfile.class})
private String lastName;
...
在序列化之前,一个AccountPojo(toString)为:
AccountPojo (id: 1, username: xyz, firstName: xyz, lastName: null, ...)
序列化:
ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
String serialized;
try {
serialized = mapper.writerWithView(JsonViews.AccountProfile.class).writeValueAsString(accountPojo);
...
序列化后,我得到:
{
"firstName":"xyz",
"lastName":"null",
...
}
视图按预期方式工作-因为我给了mapper.writerWithView()
相关的类,所以只有序列号为JsonViews.AccountProfile.class
的字段才被序列化。
问题在于null
被解释为"null"
。
什么不起作用:
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
Gson
给出了相同的结果,例如:Gson gson = new Gson();
serialized2 = gson.toJson(accountPojo);
我要寻找的是,最好在序列化中排除具有null
值的字段,或者至少使其值是null
而不是"null"
。 / p>