Home » Android » java – Parse JSON data using JSONReader or JSONObject/JSONArray

java – Parse JSON data using JSONReader or JSONObject/JSONArray

Posted by: admin June 15, 2020 Leave a comment

Questions:

I have some JSON (shown below), I am trying to parse through the entire JSON, and each object will be a new instance of a class that declares the variables below. What is the best way to do this? Should I use a JSONReader or use JSONObject and JSONArray. Ive been reading some tutorials and asking some general questions, but I havent seen any examples of how to parse out data like this.

{
    "id": 356,
    "hassubcategories": true,
    "subcategories": [
        {
            "id": 3808,
            "CategoryName": "Current Products",
            "CategoryImage": null,
            "hassubcategories": true,
            "subcategories": [
                {
                    "id": 4106,
                    "CategoryName": "Architectural",
                    "CategoryImage": "2637",
                    "hassubcategories": true,
                    "subcategories": [
                        {
                            "id": 391,
                            "CategoryName": "Flooring",
                            "CategoryImage": "2745",
                            "hassubcategories": false
                        }
                    ]
                }
            ]
        },
        {
            "id": 3809,
            "CategoryName": "Non-Current Products",
            "CategoryImage": null,
            "hassubcategories": true,
            "subcategories": [
                {
                    "id": 4107,
                    "CategoryName": "Desk",
                    "CategoryImage": "2638",
                    "hassubcategories": true,
                    "subcategories": [
                        {
                            "id": 392,
                            "CategoryName": "Wood",
                            "CategoryImage": "2746",
                            "hassubcategories": false
                        }
                    ]
                }
            ]
        }
    ]
}
How to&Answers:

if i were to do it, i will parse the whole string to a JSONObject

JSONObject obj = new JSONObject(str);

then i see that your subcategories is an JSONArray. So i will convert it like this

JSONArray arr = new JSONArray(obj.get("subcategories"));

with this you can do a loop and instantiate your class object

for(int i = 0; i < arr.length; i++)
JSONObject temp = arr.getJSONObject(i);
Category c = new Category();
c.setId(temp.get("id"));

Answer:

You can use JSON Object/ JSON Array only if the size of your json data is less than 1MB. Else you should go with JSONReader. JSONReader actually use streaming approach while JSONObject and JSONArray eventually load all the data on RAM at once which causes OutOfMemoryException in case of bigger json.

Answer:

GSON is the easiest way when you have to work with nested objects.

like this:

//after the fetched Json:
Gson gson = new Gson();

Event[] events = gson.fromJson(yourJson,  Event[].class);

//somewhere nested in the class:
static class Event{
    int id;
    String categoryName;
    String categoryImage;
    boolean hassubcategories;
    ArrayList<Event> subcategories;
}

You can check this tutorial, http://androidsmith.com/2011/07/using-gson-to-parse-json-on-android/ or http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html or http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

Answer:

this is a simple example of using Gson for modeling arraylist of objects via JsonReader :

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv = (TextView) findViewById(R.id.textviewtest);
    Task task = new Task();
    task.execute();
}

private class Task extends AsyncTask<Void, Void, ArrayList<Flower>> {

    @Override
    protected ArrayList<Flower> doInBackground(Void... params) {

        ArrayList<Flower> arrayFlowers = new ArrayList<Flower>();
        Flower[] f = null;
        try {
            String uri = "http://services.hanselandpetal.com/feeds/flowers.json";
            URL url = new URL(uri);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            Gson gson = new Gson();

            JsonReader reader = new JsonReader(new InputStreamReader(con.getInputStream()));
            f = gson.fromJson(reader, Flower[].class);

            for (Flower flower : f) {
                arrayFlowers.add(flower);
            }
        } catch (MalformedURLException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
        return arrayFlowers;
    }
    @Override
    protected void onPostExecute(ArrayList<Flower> result) {
        StringBuilder sb = new StringBuilder();
        for (Flower flower : result) {
            sb.append(flower.toString());
        }
        tv.setText(sb.toString());
    }
}

and the Object i modeled :

public class Flower {

private String category;
private double price;
private String instructions;
private String photo;
private String name;
private int productId;

public String getCategory() {
    return category;
}
public void setCategory(String category) {
    this.category = category;
}
public double getPrice() {
    return price;
}
public void setPrice(double price) {
    this.price = price;
}
public String getInstructions() {
    return instructions;
}
public void setInstructions(String instructions) {
    this.instructions = instructions;
}
public String getPhoto() {
    return photo;
}
public void setPhoto(String photo) {
    this.photo = photo;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getProductId() {
    return productId;
}
public void setProductId(int productId) {
    this.productId = productId;
}
@Override
public String toString() {
    return getProductId() + " : " + name + "\n" + price + "$" + "\n" + "\n";
}

Answer:

The example JSON data you posted does not seem to follow the JSON’s data structure. You will need to construct you data exactly the same way as taught in the third link posted by Mustafa. This is a really great tutorial. I followed the steps and it really works!

Answer:

This is the code I would use to parse all the records from a nested JSON object.

When using BSON, it returns the value as an object. So in order to use the methods associated with the actual type (int, Document, ArrayList, etc.), you have to cast the returned value to the type that is expected.

 // import java.util.ArrayList;
 // import org.bson.Document;


 Document root = Document.parse("{ \"id\" : 356, \"hassubcategories\" : true, \"subcategories\" : [{ \"id\" : 3808, \"CategoryName\" : \"Current Products\", \"CategoryImage\" : \"image.img\", \"hassubcategories\" : true, \"subcategories\" : [{ \"id\" : 4106, \"CategoryName\" : \"Architectural\", \"CategoryImage\" : \"2637\", \"hassubcategories\" : true, \"subcategories\" : [{ \"id\" : 391, \"CategoryName\" : \"Flooring\", \"CategoryImage\" : \"2745\", \"hassubcategories\" : false }] }] }, { \"id\" : 3809, \"CategoryName\" : \"Non-Current Products\", \"CategoryImage\" : \"image.img\", \"hassubcategories\" : true, \"subcategories\" : [{ \"id\" : 4107, \"CategoryName\" : \"Desk\", \"CategoryImage\" : \"2638\", \"hassubcategories\" : true, \"subcategories\" : [{ \"id\" : 392, \"CategoryName\" : \"Wood\", \"CategoryImage\" : \"2746\", \"hassubcategories\" : false }] }] }] }");

 System.out.println((root.get("id")));
 System.out.println((root.get("hassubcategories")));
 System.out.println((((Document)((ArrayList)root.get("subcategories")).get(0)).get("id")));
 System.out.println(((String)((Document)((ArrayList)root.get("subcategories")).get(0)).get("CategoryName")));
 System.out.println(((String)((Document)((ArrayList)root.get("subcategories")).get(0)).get("CategoryImage")));
 System.out.println((((Document)((ArrayList)root.get("subcategories")).get(0)).get("hassubcategories")));
 System.out.println((((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("id")));
 System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("CategoryName")));
 System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("CategoryImage")));
 System.out.println((((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("hassubcategories")));
 System.out.println((((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("id")));
 System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("CategoryName")));
 System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("CategoryImage")));
 System.out.println((((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(0)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("hassubcategories")));
 System.out.println((((Document)((ArrayList)root.get("subcategories")).get(1)).get("id")));
 System.out.println(((String)((Document)((ArrayList)root.get("subcategories")).get(1)).get("CategoryName")));
 System.out.println(((String)((Document)((ArrayList)root.get("subcategories")).get(1)).get("CategoryImage")));
 System.out.println((((Document)((ArrayList)root.get("subcategories")).get(1)).get("hassubcategories")));
 System.out.println((((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("id")));
 System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("CategoryName")));
 System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("CategoryImage")));
 System.out.println((((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("hassubcategories")));
 System.out.println((((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("id")));
 System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("CategoryName")));
 System.out.println(((String)((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("CategoryImage")));
 System.out.println((((Document)((ArrayList)((Document)((ArrayList)((Document)((ArrayList)root.get("subcategories")).get(1)).get("subcategories")).get(0)).get("subcategories")).get(0)).get("hassubcategories")));