How can I deserialize this JSON structure ?
[
{
"page": 1,
"per_page": "50"
},
[
{
"id": "IC.BUS.EASE.XQ",
"name": "ion"
},
{
"id": "OIUPOIUPOIU",
"name": "lal alalalal"
}
]
]
( I get this back from the WorldBank Api, it is a bit simplified, the exact response you find here ).
The problem is, that i get an array of objects, where the first element is a POJO and the second element is an array of POJOs of a specific type.
The only way that I found out to deserialize this is to be very generic which results in Lists and Maps.
List<Object> indicators = mapper.readValue(jsonString, new TypeReference<List<Object>>() {});
Is there a better way to deserialize this JSON to get an Array or a List, where the first element is of the Object "A" and the second a List of Objects "B" ?
If I were you, I would do something like this. It's not possible to represent your data in a good way in one list on java without using a common base class. In your case this unfortunately is Object. You can help a bit by manipulating the response list though.
ArrayNode arrayNode = (ArrayNode) mapper.readTree(this.getScrape().getScrapetext());
A a = mapper.readValue(arrayNode.get(0), A.class);
arrayNode.remove(0);
List<B> b = mapper.readValue(arrayNode.toString(), new TypeReference<List<B>>()
{
});
Given that the structure is rather irregular, in that there is no Java class definition that structurally matches a JSON Array with magic type definitions for elements by index, you probably need to do 2-pass binding.
First, you bind JSON into either List (or just Object) or JsonNode.
And from that, you can use ObjectMapper.convertValue() to extract and convert elements into actual types you want. Something like:
JsonNode root = mapper.readTree(jsonSource);
HeaderInfo header = mapper.convertValue(jsonSource.get(0),
HeaderInfo.class);
IdNamePair[] stuff = mapper.convertValue(jsonSource.get(1),
IdNamePair[].class);
would let you get typed values from original JSON Array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With