How to parse JSON from JAVA when there are random key names

How do I convert JSON to POJO when I don't know the key name?

This is my POJO:

public class Summoner {

    private Details summonerDetails;

    public Details getSummonerDetails() {
        return summonerDetails;
    }

    public void setSummonerDetails(Details summonerDetails) {
        this.summonerDetails = summonerDetails;
    }

}

      

The Details class has variables like id, name, etc. → No problem here

This is the line in my main class where I am trying to map JSON to POJO:

Summoner test = new ObjectMapper().readValue(json, Summoner.class);

      

this is an example JSON response I am getting:

{
   "randomName":{
      "id":22600348,
      "name":"Ateuzz",
      "profileIconId":546,
      "summonerLevel":30,
      "revisionDate":1378316614000
   }
}

      

if my POJO Details variable name is "randomName" the code above will work. but when I get a response with a different name than "randomName" it is not. How do I get my code to work for random names?

I am using Jackson

Sorry I can't make my problem a little clearer.

+3


source to share


1 answer


I have a solution using not only the Jackson API but also using the org.json API .

String str = "{\"randomName\":{\"id\":22600348,\"name\":\"Ateuzz\",\"profileIconId\":546,\"summonerLevel\":30,\"revisionDate\":1378316614000}}";
JSONObject json = new JSONObject(str);
Iterator<?> keys = json.keys();
while(keys.hasNext())
{
    String key = (String)keys.next();
    Details test = new ObjectMapper().readValue(json.getJSONObject(key).toString(), Details.class);

}  

      

Here I am using another JAVA Json API to convert your string to jsonObject and iterate over to get the first key value and match that against your description.



I am assuming your json format is the same as you mentioned in your question.

May this help you.

+2


source







All Articles