如何在Sping Boot 中生成动态Json

kulphzqa  于 2023-01-22  发布在  其他
关注(0)|答案(3)|浏览(146)

我写了一个API Restful服务。但是JSON现在必须改变。我必须删除输出JSON中的一些字段。
我的JSON是:

{
    "id": "10001",
    "name": "math",
    "family": "mac",
    "code": "1",
    "subNotes": [
        {
            "id": null,
            "name": "john",
            "family": null,
            "code": "1-1",
            "subNotes": null
        },
        {
            "id": null,
            "name": "cris",
            "family": null,
            "code": "1-2",
            "subNotes": null
        },
        {
            "id": null,
            "name": "eli",
            "family": null,
            "code": "1-3",
            "subNotes": null
        },
    ]
},

但是,要求是这样的:

{
    "id": "10001",
    "name": "math",
    "family": "mac",
    "code": "1",
    "subNotes": [
        {
            "name": "john",
            "code": "1-1",
        },
        {
            "name": "cris",
            "code": "1-2",
        },
        {
            "name": "eli",
            "code": "1-3",
        },
    ]
},

我可以改变它没有创建2对象(父,子)?什么是更好的解决方案?

g6ll5ycj

g6ll5ycj1#

可以在类级别忽略空字段,方法是使用@JsonInclude(Include.NON_NULL)仅包含非空字段,从而排除值为空的任何属性。

@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class testDto {

     private String id;
     private String name;
     private String family;
     private String code;
     private List<testDto> subNotes;
}

然后我的结果是

{
  "id": "10001",
  "name": "math",
  "family": "mac",
  "code": "1",
  "subNotes": [
    {
      "name": "john",
      "code": "1-1"
    },
    {
      "name": "cris",
      "code": "1-2"
    }
  ]
}

文件:使用Jackson将Java对象转换为JSON时忽略空字段的3种方法

h79rfbju

h79rfbju2#

有3种方法可以重构同一对象,而无需为您的目的创建另一个
1.@JsonIgnore位于您不希望包含的属性
1.@JsonInclude(JsonInclude.Include.NON_NULL)(如果您不希望字段始终为空)
1.@JsonInclude(JsonInclude.Include.NON_EMPTY)(如果不希望包含空列表)
第2点和第3点已在答案中共享,因此作为第一个选项

public class testDto {
 @JsonIgnore
 private String id;
 private String name;
 @JsonIgnore
 private String family;
 private String code;
 @JsonIgnore
 private List<testDto> subNotes;

}

sshcrbum

sshcrbum3#

我用Jackson注解,很有效。

import com.fasterxml.jackson.annotation.JsonInclude.Include;

public class TestDto implements Serializable {

    @JsonInclude(Include.NON_NULL)
    private String id;

    @JsonInclude(Include.NON_NULL)
    private String name;
    
    @JsonInclude(Include.NON_NULL)
    private String family;
    
    @JsonInclude(Include.NON_NULL)
    private String code;
    
    @JsonInclude(Include.NON_NULL)
    private List<TestDto> subNotes;
    
    //getter and setter ...
    
}

相关问题