Issue
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
Solution
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));
Edit: it seems that the JsonValue
annotation invalidates the serialization of the class as expected by the OP; to solve this problem one way is the use of a mixin class for the Reference
class and putting inside the JsonValue
annotation, the original Reference
class will be untouched:
@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));
Answered By - dariosicily
Answer Checked By - Marie Seifert (JavaFixing Admin)