【发布时间】: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 或空值的字段。问题是字段name、description 和type 是强制性的,即它们必须存在于生成的JSON 中,即使它们是null 或空。提供这些字段时,我没有问题。但是当它们没有提供时,
而不是这个 -
"attributes" : [
{
"type" : "Text",
"hidden" : false,
"important" : false,
...
我想要这个-
"attributes" : [
{
"name" : "",
"description" : "",
"type" : "Text",
"hidden" : false,
"important" : false,
...
在上述情况下,label、name 和 description 字段为空。此外,“具有”属性的类的形式为 -
List<Attribute> attributes;
这就是为什么,上面的JSON是这样的。
任何帮助将不胜感激。
【问题讨论】:
-
您可以将
@JsonInclude应用于特定字段。 -
@chrylis 这太多了,因为我只有 20-30 个奇数字段中的一些必填字段。代码看起来会很糟糕。
-
您将如何向软件指示哪些字段是必填项,哪些不是? (我个人会使用 Groovy 并创建一个名为
@Mandatory的注释收集器,但它相当于。) -
@JsonInclude(JsonInclude.Include.NON_NULL) 可以解决问题吗?
-
@Sikorski 有不需要包含的空字段(非空)。