0

I have a json response which is dynamic such that even the key name and index no.can change

{
"Assigned": {
    "DC": 7,
    "EmpCode": "E0104",
    "FS": 8
}
}

I want to convert it into JsonArray and fetch all the key names and values dynamically under the object 'Assigned'.But I am only getting the value name by trying this.

try {
                        //converting dynamic jsonobject to json array and fetching value as well as key name
                        JSONObject jsonObject = response.getJSONObject("Assigned");
                        Iterator x = jsonObject.keys();
                        JSONArray jsonArray = new JSONArray();
                        while (x.hasNext()) {
                            String key = (String) x.next();
                            jsonArray.put(jsonObject.get(key));
                    }
                        Toast.makeText(RolesActivity.this,jsonArray.toString(), Toast.LENGTH_LONG).show();
                        Log.d("jsonarray",jsonArray.toString());

                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                        Toast.makeText(RolesActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
                    }
user8601021
  • 219
  • 3
  • 18

2 Answers2

1

You can get the JSONObject's keys list by calling JSONObject.keys() (as Iterator), or JSONObject.names() (as JSONArray)

After that you can iterate through the keys, and get each key's value by using JSONObject.getString(key)

Vladyslav Matviienko
  • 10,610
  • 4
  • 33
  • 52
0

First create a pojo class

  private HashMap<String, String> parseResponse(){

    String json = ""; //  your json string

    Gson gson = new Gson();

    Response response =  gson.fromJson(json, Response.class)

    return response.getAssigned();

}


public class Response {

    @SerializedName("Assigned")
    private HashMap<String, String> assigned;

    public HashMap<String, String> getAssigned() {
        return assigned;
    }
}

than parse with Gson library. You can read key and values from assigned Hashmap.

toffor
  • 1,219
  • 1
  • 12
  • 21