ObjectMapper将null序列化为字符串

时间:2019-09-25 13:21:12

标签: java json jackson

模型类:

@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>

0 个答案:

没有答案