3

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" ?

2 Answers 2

2

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>>()
    {
    });
Sign up to request clarification or add additional context in comments.

1 Comment

@Oskar_Kjellin: Thanks, this solved my problem. Please correct just 2 things in your answer: 1.) List<B> b = mapper.readValue(arrayNode.**get(0)**.toString() works correct. 2.) i changed this.getScrape()... to "jsonString" in the original question for understandability's sake, could you please change it in the answer as well ? Thx.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.