0

I have the following JSON coming from a server in the variable of StringBuffer called response which I can see in the output after making it toString().

[{"_id": "Grocery", "Categories": [{"Pulses and Grains": ["Dals"]}, {"Beverages": ["Juices", "Tea", "Coffee", "Soft Drinks"]}]}, {"_id": "Stationary", "Categories": [{"Chart Paper": ["A4 Size Chart Paper", "A3 Size Chart Paper"]}]}]

The code I have written till now which is not solving my purpose:

JSONArray ar=new JSONArray(response.
JSONObject jObject = ar.getJSONObject(0);
JSONObject jObject = ar.getJSONObject(1);
String JObjectString=jObject.toString();
System.out.println("The JObject String "+JObjectString);

I need to store each and every element which includes "Pulses and Grains", "Dals", "Tea", "A3 size paper" etc. and every element in that array in a String variable. How can I access each and every element from the hierarchy since it is too nested.?

1 Answer 1

2

Since JSONObject implements the Map interface, you can list all of its field name and values with method

jObject.entrySet()

If you know the name of the fields in advance, you can retrieve them by name:

JSONArray categories = jObject.get("Categories");

But I would rather suggest to use some nice JSON libraries such as google's Gson, so that you can just define your data classes and then automagically parse the JSON into a hierarchy of classes:

class Element {
   String _id;
   List<Category> categories;
   public Element(){}
}

class Category {
   private List<Entry> entries;
   public Category (){}
}

class Entry {
   private List<String> units;
   public Entry (){}
} 

Then you can parse the json into objects:

Gson gson = new Gson();
Element[] elements = gson.fromJson(jsonString, Element[].class);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.