Reputation: 425073
Is there a way using, Jackson annotations, to have a have given field serialised to 2 json fields.
Like the reverse of @JsonAlias
which deserialises multiple json field to the one field.
Eg
class Foo {
@SomeAnnotation("field2")
String field1;
}
serialising as:
{
"field1" : "xyz",
"field2" : "xyz"
}
Is there a something like @SomeAnnotation
?
——
Note: This is not a “should” I do this (it’s an imposed requirement), it’s a “how” I do this (elegantly).
Upvotes: 4
Views: 1616
Reputation: 45319
A simple solution to this may be to just add two getters for field1
:
class Foo {
private String field1 = "blah";
public String getField1() {
return field1;
}
public String getField2() {
return field1;
}
}
Jackson will create a field for each getter, following the javabeans naming convention:
{"field1":"blah","field2":"blah"}
An alternative to this may be @com.fasterxml.jackson.annotation.JsonAnyGetter
, which can afford you even more flexibility:
class Foo {
private String field1 = "blah";
public String getField1() {
return field1;
}
@JsonAnyGetter
public Map<String, Object> getAny() {
Map<String, Object> m = new HashMap<>();
m.put("field2", this.field1);
m.put("field3", this.field1.toUpperCase());
return m;
}
}
Producing:
{"field1":"blah","field3":"BLAH","field2":"blah"}
Upvotes: 4