简体   繁体   中英

Ignore enclosing braces with JSON parser while serializing object in Java

I have the following classes:

@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;
    }

}

When serializing to XML the format is as expected, but when I try to serialize to JSON I get the following

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

And I need it to be:

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

the braces enclosing the reference list I need it to be ignored without the attribute name

You can annotate the ref field in your Reference class with the JsonValue annotation that indicates that the value of annotated accessor is to be used as the single value to serialize for the instance :

@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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM