I have the following json sample
[
{
"owners": [
{
"id": 1,
"name": "abc",
"accounts": [
{
"number": 5,
"region": "IND"
},
{
"number": 6,
"region": "US"
}
]
},
{
"id": 2,
"name": "pqr",
"accounts": [
{
"number": 7,
"region": "UK"
}
]
}
],
"prop1": "xyz",
"prop2": "abc"
},
{
"owners": [
{
"id": 10,
"name": "she",
"accounts": [
{
"number": 12,
"region": "DE"
},
{
"number": 31,
"region": "MK"
}
]
},
{
"id": 21,
"name": "cdf",
"accounts": [
{
"number": 27,
"region": "PK"
}
]
}
],
"prop1": "qse",
"prop2": "vcd"
}
]
I am trying to parse the above json to my java class Owner which is defined below:
@Data
public class Owner {
private List<Entry> entries;
private String prop1;
private String prop2;
}
@Data
public class Entry {
private int id,
private String name,
private List<Account> accounts;
}
@Data
public class Account {
private int number;
private String region;
}
I am getting the json as http response and assigning it to
List<Owner> owners = restTemplate.exchange(url, GET, new HttpEntity<>(httpHeaders),
new ParameterizedTypeReference<>() {
});
I am using spring boot and jackson library is in classpath, so I expect the nested classes will be populated.
In the Owner POJO I see only prop1 and prop2 are populated but the Entry list is null.
As there is no key for the list of json objects, the List is not getting populates. Is there any annotations or by using ObjectMapper directly this can be achieved?
Can someone guide me on how to properly parse and get all fields populated in my java POJO
>Solution :
The property "owners" in the incoming JSON should be deserialized into a list of entities entries in the Owner class.
To instruct Jackson that "owners" should be mapped to entries you can use @JsonProperty annotation.
@Data
public class Owner {
@JsonProperty("owners")
private List<Entry> entries;
private String prop1;
private String prop2;
}
This would be enough to get the incoming JSON to be deserialized successfully.
By the way, this mess in names looks confusing, it would be a good idea to make them aligned.