【问题标题】:Jackson: Ignore empty fields except those that are mandatory with respect to the projectJackson:忽略空白字段,除了项目中的必填字段
【发布时间】:2023-03-17 06:50:01
【问题描述】:

下面是一个 POJO 类(处于某种嵌套级别的类之一),它的一个对象,我正在使用 Jackson 将其序列化为 JSON。

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Attribute {

    private String label;
    private String name;        // Mandatory
    private String description; // Mandatory
    private String type;        // Mandatory
    private Boolean hidden;
    private Boolean important;
    ...

使用@JsonInclude(JsonInclude.Include.NON_EMPTY) 仅包括具有非null 或空值的字段。问题是字段namedescriptiontype 是强制性的,即它们必须存在于生成的JSON 中,即使它们是null 或空。提供这些字段时,我没有问题。但是当它们没有提供时,

而不是这个 -

"attributes" : [ 
    {
        "type" : "Text",
        "hidden" : false,
        "important" : false,
        ...

我想要这个-

"attributes" : [ 
    {
        "name" : "",
        "description" : "",
        "type" : "Text",
        "hidden" : false,
        "important" : false,
        ...

在上述情况下,labelnamedescription 字段为空。此外,“具有”属性的类的形式为 -

List<Attribute> attributes;

这就是为什么,上面的JSON是这样的。

任何帮助将不胜感激。

【问题讨论】:

  • 您可以将@JsonInclude应用于特定字段。
  • @chrylis 这太多了,因为我只有 20-30 个奇数字段中的一些必填字段。代码看起来会很糟糕。
  • 您将如何向软件指示哪些字段是必填项,哪些不是? (我个人会使用 Groovy 并创建一个名为 @Mandatory 的注释收集器,但它相当于。)
  • @JsonInclude(JsonInclude.Include.NON_NULL) 可以解决问题吗?
  • @Sikorski 有不需要包含的空字段(非空)。

标签: java json jackson


【解决方案1】:

我认为@chrylis 的建议正是您想要的。在字段级别使用@JsonInclude(默认值为JsonInclude.Include.ALWAYS)注释特定字段以覆盖类级别@JsonInclude(JsonInclude.Include.NON_EMPTY) 的想法。下面是一个例子:

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public static class Attribute {

    private String label;
    @JsonInclude
    private String name;        // Mandatory
    @JsonInclude
    private String description; // Mandatory
    @JsonInclude
    private String type;        // Mandatory

【讨论】:

    猜你喜欢
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 2014-03-26
    相关资源
    最近更新 更多