-3

The API I'm using provides a JSON output. How can I parse it on android studio? I've never seen a JSON printout like this before.

{
"market":   {
        "100": {
        "name": "forexample",
        "surname": "forexample2"
},
         "101": {
        "name": "forexample3",
        "surname": "forexample4"
},

.
.
.

 "999": {
        "name": "forexampleXX",
        "surname": "forexampleXX"
}
}
}

"101" continues to increase by 1. It's going to be too long to make individual identifications. What's the shortest way?

Bill
  • 11
  • 3

4 Answers4

0

This is how you get data from your desired Object

    JSONObject json= new JSONObject();
    json = response.getJSONObject("market");
    Iterator<String> iter = json.keys();//here you get 100,101,102 ....without accessing individually
    while (iter.hasNext()) {
    String key = iter.next();
    try {
        Object value = json.get(key);//Here you get you object values
    } catch (JSONException e) {
        // Something went wrong!
    }
    }

Further details read this

Feel free to ask if anything is not clear.

Syed Hamza Hassan
  • 710
  • 1
  • 11
  • 24
0

Your "market" JSON should be JSONArray. Show you can use content with index.

Change your API output. Like,

{
"market":   [
         {
        "name": "forexample",
        "surname": "forexample2"
         },

         {
        "name": "forexample3",
        "surname": "forexample4"
         },

.
.
.

    {
        "name": "forexampleXX",
        "surname": "forexampleXX"
    }
 ]
}
Abhay Koradiya
  • 2,068
  • 2
  • 15
  • 40
0

You could use https://github.com/google/gson. And transform the json to something like

HashMap<String,HashMap<String,Person>> map

This article could help for parsing this type- Deserializing Generic Types with GSON

Person would be a class with name and surname. First get the first level keys. -> map.keySet(), and for each new hashmap get the next level key. Something like

for (String key: map.keySet()) {
 HashMap < String, Person > personMap = map.get(key);
 for (String personKey: personMap() {
   Person person = map.get(personKey);
   // do what you want with the person object
  }
 }
Boldijar Paul
  • 5,405
  • 9
  • 46
  • 94
0

You can use GSON library it is very famous library add it like this

implementation 'com.google.code.gson:gson:2.8.2'

then u can parse it like this

Market market = new Gson().fromJson( jsonString , Market.class);

where Market Class will be

public class Market {
     public HashMap<Integer ,  User > result ;
}

AND

public class User{ 
    public String name ;
    public String surname ;
}

Or u can parse it without a class like this

HashMap<String,HashMap<String, User>>  result = gson.fromJson( jsonString , new TypeToken<HashMap<String,HashMap<String, User>>>() {
                        }.getType());

Hope this will help you @Bill.

Diaa Saada
  • 1,026
  • 1
  • 12
  • 22