不要包括杰克逊的空对象



我正在尝试用spring引导创建json。

类别:

public class Person {
private String name;
private PersonDetails details;
//     getters and setters...
}

含义:

Person person = new Person();
person.setName("Apple");
person.setDetails(new PersonDetails());

因此,有一个Person的实例,details为空,这正是Jackson返回的:

"person": {
"name": "Apple",
"details": {}
}

我想要没有空括号的json{}:

"person": {
"name": "Apple"
}

这个问题对我没有帮助:

  • 如何告诉Jackson在反序列化过程中忽略空对象
  • 如何忽略";空";或json中的空属性,全局使用Spring配置

更新1:

我正在使用Jackson 2.9.6

如果没有自定义序列化程序,jackson将包含您的对象。

解决方案1:用空替换新对象

person.setDetails(new PersonDetails());

带有

person.setDetails(null);

并添加

@JsonInclude(Include.NON_NULL)
public class Person {

解决方案2:自定义序列化程序

public class PersonDetailsSerializer extends StdSerializer<PersonDetails> {
public PersonDetailsSerializer() {
this(null);
}
public PersonDetailsSerializer(Class<PersonDetails> t) {
super(t);
}
@Override
public void serialize(
PersonDetails personDetails, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException {
// custom behavior if you implement equals and hashCode in your code
if(personDetails.equals(new PersonDetails()){
return;
}
super.serialize(personDetails,jgen,provider);
}
}

以及在您的PersonDetails

public class Person {
private String name;
@JsonSerialize(using = PersonDetailsSerializer.class)
private PersonDetails details;
}

相关内容

最新更新