2

Assume that I get this JSon Response from webservice:

{
    "id":13,
    "name":"Alireza",
    "required_id":"14",
    "all_friends_id_and_name":{
        "28":"Hassan",
        "21":"Mohammad",
        "68":"Ali",
        "14":"Taha",
        "96":"Darya"
    }
}

In this response required_id value specifies that I need a friend name with id 14, so in all_friends_id_and_name object I should get the value of "14" (Taha) and use it in my app.

I'm using retrofit2 and gson libraries.

How to get property of an object which has non-fixed keys?

piet.t
  • 11,718
  • 21
  • 43
  • 52
Alireza Noorali
  • 3,129
  • 2
  • 33
  • 80
  • see https://stackoverflow.com/questions/20419217/to-get-all-the-keys-in-jsonobject-into-string-array and https://stackoverflow.com/questions/7091054/how-i-can-get-all-the-keys-from-a-string-which-somehow-looks-like-json-string , I dont think gson can be used – Manohar Sep 10 '18 at 07:15

2 Answers2

2

For Native approach, You can Try with Iterator .

An iterator is an object that enables a programmer to traverse a container, particularly lists.

 "all_friends_id_and_name":{
        "28":"Hassan",
        "21":"Mohammad",
        "68":"Ali",
        "14":"Taha",
        "96":"Darya"
    }

For the above section, Your LOGIC will be

     JSONObject jsonData = new JSONObject("Json_response");
          Iterator  iteratorObj = jsonData .keys();
           while (iteratorObj.hasNext())
            {
                String str_json_Key = (String)iteratorObj.next();
                 // Print=28,21....96
             }
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
0

Here is your Json:

{
    "id":13,
    "name":"Alireza",
    "required_id":"14",
    "all_friends_id_and_name":{
        "28":"Hassan",
        "21":"Mohammad",
        "68":"Ali",
        "14":"Taha",
        "96":"Darya"
    }
}

Try by doing like this :

 try {

     JSONObject jsonObject; // it should be your above JsonObject 

            Iterator<?> keys = jsonObject.keys();

            while (keys.hasNext()) {
                String key = (String) keys.next();
                System.out.println("Mykey: " + key + " value: " + jsonObject.getString(key));    
            }


    } catch (JSONException e) {
        e.printStackTrace();
    }
Muhammad Zahab
  • 1,049
  • 10
  • 21