László Csiki László Csiki - 6 months ago 72
Java Question

Android: How to get JSON object keys from this json:

This is the JSON array:

{
"server_response": [{
"Total": "135",
"Paid": "105",
"Rest": "30"
}]
}


So, how can i get the object names? I want to put them in separate TextView.
Thanks.

Answer

Put this out side everything. I mean outside onCreate() and all.

private <T> Iterable<T> iterate(final Iterator<T> i){
    return new Iterable<T>() {
        @Override
        public Iterator<T> i() {
            return i;
        }
    };
}

For getting the names of objects :

    try
    {
        JSONObject jsonObject = new JSONObject("{" +"\"server_response\": [{" +"\"Total\": \"135\"," +"\"Paid\": \"105\"," +"\"Rest\": \"30\"" +"}]"+"}";);
        JSONArray jsonArray = jsonObject.getJSONArray("server_response");
        JSONObject object = jsonArray.getJSONObject(0);

        for (String key : iterate(object.keys())) 
        {
            // here key will be containing your OBJECT NAME YOU CAN SET IT IN TEXTVIEW.
            Toast.makeText(HomeActivity.this, ""+key, Toast.LENGTH_SHORT).show();
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
Comments