0

I need to parse a json with the structure as follows:

{
    "names": {
        "nameOne": {
            "item": "my item"
        },
        "nameOther": {
            "item": "my item 2"
        },
        ... more elements with no prevously known attribute name
    }
}

How could i retrieve it if i do not know how many nameOne, nameOther...nameX exist? My problem is to model that json, so i can not use a SerializedName. I think maybe exists something like a hashmap to store that objects.

Billyjoker
  • 729
  • 1
  • 10
  • 31

3 Answers3

2

use like this

    @Expose
    @SerializedName("names")
    private HashMap<String, String> map;

map key will contains 'nameOne,.......'

use Gson as json parsing

Basi
  • 3,009
  • 23
  • 28
0

This is not valid JSON structure. Anyway you can check this

How to parse JSON Array (Not Json Object) in Android

for parsing a JSON list it is not important how many elements will be in list. Do the simple for loop through the list elements and voila. Or even better use create something like this to parse a response :

public class Foo {
private List<Names> objects;
}

and you can use serializable here

Djaf
  • 256
  • 1
  • 6
0

you can loop through jsonObject's keys and add them to a map

Object obj = new JSONParser().parse(new FileReader("JSONExample.json"));

JSONObject jo = (JSONObject) obj;

Iterator<String> keys = jo.keys();

while(keys.hasNext()) {
    String key = keys.next();
    if (jo.get(key) instanceof JSONObject) {
          // do something with jsonObject here      
    }
}
puya ars
  • 327
  • 2
  • 9