Issue
I'm wondering if there is any way to deserialize several JSON fields to just one Java property. E.g. given this JSON:
{
"id" : "1",
"name" : "Bartolo",
"address" : "whatever",
"phone" : "787312212"
}
public class Person {
public String id;
public String name:
@JsonProperty(names = {"address", "phone"}) //something like this
public String moreInfo;
}
so moreInfo
equals to "whatever, 787312212"
or something similar.
Is this possible without using custom deserializer?
Solution
You could use the @JsonCreator
annotation like following:
String json = {"id" : "1", "name" : "Bartolo", "address" : "whatever", "phone" : "787312212" }
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json , Person.class);
and in the constructor of your Person class add this
@JsonCreator
public Person(@JsonProperty("address") String address, @JsonProperty("phone") String phone) {
this.moreInfo = address + "," phone;
}
Answered By - NickAth
Answer Checked By - Marie Seifert (JavaFixing Admin)