Manipulate json object

Asked

Viewed 454 times

1

I got 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’ve tried the following methods but both end up being wrong:
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 store the value of image of the index 2 array home in the variable image?

  • Already tried using the library Gson google?

1 answer

2


What happens is that your home is a array of objects, so try it like this:

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 for your code to work. Now, to get the index 2 as you asked, I believe it will be necessary to iterate on the array until you reach the desired index.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.