在 Java 中序列化对象时忽略带有 JSON 解析器的大括号

Ignore enclosing braces with JSON parser while serializing object in Java

我有以下 类:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class User {

    private String id;
    private List<Reference> references;
.....
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Reference {

    @JacksonXmlProperty(isAttribute = true)
    private String ref;

    public Reference(final String ref) {
        this.ref = ref;
    }

    public Reference() { }

    public String getRef() {
        return ref;
    }

}

当序列化为 XML 时,格式符合预期,但是当我尝试序列化为 JSON 时,我得到以下内容

"users" : [
  {
      "references" : [
      {
        "ref": "referenceID"
      }
    ]
  }
]

我需要它是:

"users" : [
  {
      "references" : [
        "referenceID"
    ]
  }
]

包含引用列表的大括号我需要在没有属性名称的情况下忽略它

您可以使用 JsonValue 注释来注释 Reference class 中的 ref 字段,表明 注释访问器的值是用作实例序列化的单个值:

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Reference {

    @JacksonXmlProperty(isAttribute = true)
    @JsonValue //<-- the new annotation
    private String ref;

    public Reference(final String ref) {
        this.ref = ref;
    }

    public Reference() { }

    public String getRef() {
        return ref;
    }

}

User user = new User();
user.setReferences(List.of(new Reference("referenceID")));
//it prints {"references":["referenceID"]}
System.out.println(jsonMapper.writeValueAsString(user));

Edit:似乎 JsonValue 注释使 class 的序列化无效,正如 OP 所期望的那样;解决这个问题的一种方法是为 Reference class 使用 mixin class 并将原始 Reference [=28] 放入 JsonValue 注释中=] 将保持不变:

@Data
public class MixInReference {
    @JsonValue
    private String ref;
}


ObjectMapper jsonMapper = new ObjectMapper();
//Reference class is still the original class
jsonMapper.addMixIn(Reference.class, MixInReference.class);
////it prints {"references":["referenceID"]}
System.out.println(jsonMapper.writeValueAsString(user));