Handle json object

1

I have the following json :

{
   "home":[
      {
         "id":"1",
         "menu":"1",
         "title":"Titulo 1",
         "image":"image01.jpg",
         "url":"http:\/\/www.exemplo.pt\/images\/image01.jpg"
      },
      {
         "id":"2",
         "menu":"3",
         "title":"Titulo 2",
         "image":"image02.jpg",
         "url":"http:\/\/www.exemplo.pt\/images\/image02.jpg"
      },
      {
         "id":"3",
         "menu":"4",
         "title":"Titulo 3",
         "image":"image03.jpg",
         "url":"http:\/\/www.exemplo.pt\/images\/image03.jpg"
      }
   ]
}

I have tried the following methods but both end up giving error:
JSONArray

try {
    JSONArray JOBJECT = new JSONArray(jsonString);
    JSONArray home = JOBJECT.getJSONArray(0);
    JSONArray home_idx_1 = home.getJSONArray(0);
    String image = home_idx_1.getString(0);

    Log.v("view content", image);
} catch (JSONException e) {
    e.printStackTrace();
}

JSONObject

try {
    JSONObject JOBJECT = new JSONObject(jsonString);
    JSONObject home = JOBJECT.getJSONObject("home");
    JSONArray home_idx_1 = home.getJSONArray("0");
    String image = home_idx_1.getString("image");

    Log.v("view content", image);
} catch (JSONException e) {
    e.printStackTrace();
}

How can I do to store the value of image of index 2 of array home in variable image ?

    
asked by anonymous 25.11.2014 / 17:06

1 answer

2

What happens is that your home is an array of objects, so try it out:

try {
    JSONObject JOBJECT = new JSONObject(jsonString);
    JSONArray array = JOBJECT.getJSONArray("home");
    JSONObject home_idx_1 = array.getJSONObject(0);
    String image = home_idx_1.getString("image");

    Log.v("view content", image);
} catch (JSONException e) {
    e.printStackTrace();
}

This is for your code to work. Now, to get index 2 as you asked, I believe it will be necessary to iterate over array until it reaches the desired index.

    
25.11.2014 / 17:30