facundop facundop - 1 month ago 7
Java Question

Parsin JSON with JAVA when there is a random KEY name

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

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 have variables like id, name, etc. -> No issues here

This is the line in my Main class where I try to map the JSON to a POJO:

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


this is a JSON response example I receive:

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


if my POJO Details member variable name is "randomName", above code will work. but when I get a response with a different name than "randomName", it doesn't. How do I make my code work for random names?

I'm using Jackson

I'm sorry I can't make a little more clear my issue.

Answer

I have solution using not only jackson API but with the use of org.json API also.

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 have use another JAVA Json API to convert your string into jsonObject and than iterate it to get your first key value and map that to your class Details.

I assume that your json format is same as you have mention in your question.

May this will help you.