从Jackson对象Map器中排除空数组

gstyhher  于 2022-11-09  发布在  其他
关注(0)|答案(3)|浏览(176)

我正在使用Jackson ObjectMapper从Java对象树构建JSON。我的一些Java对象是集合,有时它们可能是空的。因此,如果它们是空的,ObjectMapper会生成我:"attributes": [],,我想从结果中排除这些类型的空JSON数组。

SerializationConfig config = objectMapper.getSerializationConfig();
config.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
config.set(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);

我从this post中了解到我可以使用:

config.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);

但这给我带来了一个错误:

Caused by: java.lang.IllegalArgumentException: Class com.mycomp.assessments.evaluation.EvaluationImpl$1 has no default constructor; can not instantiate default bean value to support 'properties=JsonSerialize.Inclusion.NON_DEFAULT' annotation.

那么,我应该如何防止这些空数组出现在结果中呢?

mgdq6dx1

mgdq6dx11#

您应该使用:

config.setSerializationInclusion(JsonSerialize.Inclusion.NON_EMPTY);

Jackson一号或

config.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

Jackson2

h4cxqtbf

h4cxqtbf2#

一个很好的例子描述:

  • JsonInclude.包含.非空值
  • JSON包含.包含.不存在
  • JSON包含.包含.非空

输入:https://www.logicbig.com/tutorials/misc/jackson/json-include-non-empty.html

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Employee {
  private String name;
  private String dept;
  private String address;
  private List<String> phones;
  private AtomicReference<BigDecimal> salary;
    .............
}

public class ExampleMain {
  public static void main(String[] args) throws IOException {
      Employee employee = new Employee();
      employee.setName("Trish");
      employee.setDept("");
      employee.setAddress(null);
      employee.setPhones(new ArrayList<>());
      employee.setSalary(new AtomicReference<>());

      ObjectMapper om = new ObjectMapper();
      String jsonString = om.writeValueAsString(employee);
      System.out.println(jsonString);
  }
}

=====〉结果:
如果我们根本不使用@JsonInclude注解,那么上面示例的输出将是:{“姓名”:“翠西”,“部门”:“",“地址”:空,“电话”:[],“工资”:空}
如果我们在Employee类上使用@JsonInclude(JsonInclude.Include.NON_NULL),则输出将为:{“姓名”:“翠西”,“部门”:“",“电话”:[],“薪金”:空}
如果我们使用@JsonInclude(JsonInclude.Include.NON_ABSENT),则输出将为:{“姓名”:“崔西”,“部门”:“",“电话”:[]}
如果我们使用@JsonInclude(JsonInclude.Include.非空):{“姓名”:“崔西”}

r6l8ljro

r6l8ljro3#

如果您可以修改要序列化的对象,也可以直接在字段上放置注解,例如(Jackson 2.11.2):

@JsonProperty
@JsonInclude(JsonInclude.Include.NON_EMPTY)
private Set<String> mySet = new HashSet<>();

通过这种方式,不需要进一步配置ObjectMapper

相关问题