-1

I'm trying to parse this JSON in my app, im not sure if its well structured or not but that's what Im getting from the api for now. I have no idea how to get the key"number" of each Jsonobject and how to parse an jsonobject of jsonobjects, any help on that

{
   "response":"1",
   "data":{
      "1":{
         "category_name":"first",
         "image_url":""
      },
      "2":{
         "category_name":"secondType",
         "image_url":""
      },
      "3":{
         "category_name":"Night",
         "image_url":""
      }
   }
}

here's my try to parse it

if (isAdded() && getActivity() != null && response.getString("response").equals("1")) {
                    JSONObject jsonObject = response.getJSONObject("data");
                    for (int i = 0; i < jsonObject.length(); i++) {
                       CategoryLookBookModel lookBookModel = new CategoryLookBookModel();
                        lookBookModel.setCategory_name(jsonObject.get(""+i).getString("category_name"));
                        lookBookModel.setCategory_image(jsonArray.getJSONObject(i).getString("image_url"));
                        list.add(lookBookModel);
                    }
George2456
  • 340
  • 5
  • 19

4 Answers4

2

Your JSON Key is Dynamic. So You should use Iterator.

Using Iterator, you can iterate all elements of a list in either direction. You can access next element by calling next() method .

 JSONObject jsonObject = response.getJSONObject("data");
                  Iterator  iteratorObj = jsonObject .keys();
                   while (iteratorObj.hasNext())
                    {
                        String Str_KEY = (String)iteratorObj.next();
                        System.out.println("Key: " + Key + "Intellij_Amiya" + Str_KEY );             

                        // Do your Code// 

                    }
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
1

Try this,

JSONObject json = response.getJSONObject("data");
Iterator<String> keys_iteration = json.keys();

while (keys_iteration.hasNext()) {
    String key = keys_iteration.next();  // this will give you 1,2,3....
   JSONObject jsonData = response.getJSONObject(key); // object of individual key

    CategoryLookBookModel lookBookModel = new CategoryLookBookModel();
                    lookBookModel.setCategory_name(jsonData.getString("category_name"));
                    lookBookModel.setCategory_image(jsonData.getString("image_url"));
                    list.add(lookBookModel);
}
Exigente05
  • 2,161
  • 3
  • 22
  • 42
1

If you are struggling manually navigating through the json (as you are doing right now) another option is to deserialize the json into POJO's (plain old Java objects).

What that does is allow you to work with objects. You can define a POJO for your JSON structure such as this:

public class CategoryImageData {
    public String response;
    public Map<String, CategoryImage> data;
}

public class CategoryImage {
    public String category_name;
    public String image_url;
}

Then you can use a library such as Gson (see https://github.com/google/gson) to deserialize your json into a object:

private static final Gson gson = new Gson();

CategoryImageData data = gson.fromJson(jsonString, CategoryImageData.class);

Now you have a CategoryImageData object containing all the json data.

You could iterate over the Map in the data to get the key number:

for(Map.Entry<String, CategoryImage> entry : data.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue().image_url);
}
nbokmans
  • 5,492
  • 4
  • 35
  • 59
1

try this and add this compile 'com.google.code.gson:gson:2.7' in build.gradle

please create your JSON response like below

{
    "response": "1",
    "data": [{
            "category_name": "first",
            "image_url": ""
        },
        {
            "category_name": "secondType",
            "image_url": ""
        },
        {
            "category_name": "Night",
            "image_url": ""
        }
    ]
} 

and create model in your package like below

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.util.List;



public class Example {

    @SerializedName("response")
    @Expose
    private String response;
    @SerializedName("data")
    @Expose
    private List<Categories> data = null;

    public String getResponse() {
        return response;
    }

    public void setResponse(String response) {
        this.response = response;
    }

    public List<Categories> getData() {
        return data;
    }

    public void setData(List<Categories> data) {
        this.data = data;
    }
    public class Categories {

        @SerializedName("category_name")
        @Expose
        private String categoryName;
        @SerializedName("image_url")
        @Expose
        private String imageUrl;

        public String getCategoryName() {
            return categoryName;
        }

        public void setCategoryName(String categoryName) {
            this.categoryName = categoryName;
        }

        public String getImageUrl() {
            return imageUrl;
        }

        public void setImageUrl(String imageUrl) {
            this.imageUrl = imageUrl;
        }

    }

}

and in your response parse below like

Example example = new Gson().fromJson(jsonResponseString,Example.class);
Bhupat Bheda
  • 1,968
  • 1
  • 8
  • 13