user1302569
user1302569

Reputation: 7191

Get some data from JSON

I need some help with JSON. I get a JSON as follows:

{
    "1": {
    "id": "1",
    "position": "1",
    "Category": {
        "id": "1",
        "position": "1",
        "created_at": "2012-10-24 15:42:47",
        "updated_at": "2012-11-13 13:46:25",
        "name": "ABCD"
                }
          }
 }

and I want to get all data from field Category.

I try this way:

JSONObject categoryObject = json.getJSONObject("Category"); 

but I get error:

no value for Category. How I can get data for Category field?

Upvotes: 0

Views: 110

Answers (3)

ashakirov
ashakirov

Reputation: 12350

try {
        String jsonString="{\"1\":{\"id\":\"1\",\"position\":\"1\",\"Category\":{\"id\":\"1\",\"position\":\"1\",\"created_at\":\"2012-10-24 15:42:47\",\"updated_at\":\"2012-11-13 13:46:25\",\"name\":\"ABCD\"}}}";
        JSONObject jsonObject=new JSONObject(jsonString);
        JSONObject jsonObject1= jsonObject.getJSONObject("1");

        String id=jsonObject1.getString("id");
        String position =jsonObject1.getString("position");

        JSONObject jsonObjectCategory= jsonObject1.getJSONObject("Category");

        String idCategory=jsonObjectCategory.getString("id");
        String positionCategory=jsonObjectCategory.getString("position");
        String createdAt=jsonObjectCategory.getString("created_at");
        String updatedAt=jsonObjectCategory.getString("updated_at");
        String name=jsonObjectCategory.getString("name");

        Log.e(getClass().getSimpleName(), "name="+name +"; created_at= "+createdAt);
    } catch (JSONException e) {
        e.printStackTrace();
    }

Upvotes: 0

Ilya
Ilya

Reputation: 29673

JSONObject categoryObject = json.getJSONObject("1").getJSONObject("Category");  
categoryObject.get("id"); // return 1  
categoryObject.get("position"); // return 1   
categoryObject.get("name"); // return "ABCD"

etc

Upvotes: 1

Vetalll
Vetalll

Reputation: 3702

You should to do folowing.

JSONObject json1 = json.getJSONObject("1");

JSONObject categoryObject = json1.getJSONObject("Category");

You can see hierarhy on the site

Upvotes: 1

Related Questions