Home > other >  Ignore enclosing braces with JSON parser while serializing object in Java
Ignore enclosing braces with JSON parser while serializing object in Java

Time:02-01

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

CodePudding user response:

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));
  •  Tags:  
  • Related