Naser khosravi Naser khosravi - 5 months ago 14
Android Question

What is diffrence between get and getJSONObject in class Json in java

i have JsonFormat :


{"product":[{"description":"my describtion","isStock":"instock","linkArray":[{"link":"http://rozinleather.ir/demo/wp-content/uploads/2016/05/8e4996-1.jpg"},{"link":"http://rozinleather.ir/demo/wp-content/uploads/2016/05/19b37f-1.jpg"},{"link":"http://rozinleather.ir/demo/wp-content/uploads/2016/05/33bc31-1.jpg"},{"link":"http://rozinleather.ir/demo/wp-content/uploads/2016/05/459e33-1.jpg"},{"link":"http://rozinleather.ir/demo/wp-content/uploads/2016/05/a18f87-1.jpg"},{"link":"http://rozinleather.ir/demo/wp-content/uploads/2016/05/c58d16-1.jpg"},{"link":"http://rozinleather.ir/demo/wp-content/uploads/2016/05/d952f8-2.jpg"}]}],"success":1}

i can't understand how to get nested JsonObject.

thank you.

Answer

First you need to create a JSONObject passing the JSON string as a parameter:

JSONObject jsonObject = new JSONObject(jsonString);

And then, depending on your needs, you may want to fetch an array, another JSON object or a value of the JSONObject:

JSONArray productArray = jsonObject.getJSONArray("product");
Integer success = jsonObject.getInt("success");

You can iterate over a JSONArray and get all the elements of the array, and do what you want with each object of the array (extract values, fetch arrays or objects of the element, etc):

for (int i = 0; i < productArray.length(); i++) {
    JSONObject product = productArray.getJSONObject(i);
    String description = product.getString("description");
    ...
}

Read more about JSONObject and JSONArray available methods:

JSONObject

JSONArray