Reputation: 26054
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"
}
deserialize it to this class:
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?
Upvotes: 0
Views: 1130
Reputation: 69
Another solution, if you don't want to know/handle other fields in the object, but decided to still receive these fields (maybe for logging purposes), then you can put them in a key-value store(Map)
@Getter
private final Map<String, Object> otherFields = new HashMap<>();
@JsonAnySetter
public void set(String name, Object value) {
otherFields.put(name, value);
}
Note that if you have any field with the same name as the Map field(like 'otherFields' in the example above), then you can get MismatchedInputException
Upvotes: 0
Reputation: 1112
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;
}
Upvotes: 1