0

I am trying to access JSON object keys using the following code.

JSONObject mainObject = new JSONObject(response);
JSONObject posts = mainObject.getJSONObject("_id");
Map<String, JSONObject> map = (Map<String,JSONObject>)posts.getMap();
ArrayList<String> list = new ArrayList<String>(map.keySet());
System.out.println(list);

My JSON Array is:

[{"_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"]}]}]

My project is not any Android project but I am bounded to using this line just to get all the keys and their values of JSON in my project. The problem with this is that it is showing red line under .getMap() and is saying it is unable to find symbol. Please let me know what I should import to get this done, keeping in mind that this is not any Android project

Srikar V
  • 5
  • 3

1 Answers1

0

Use better Gson.

'''    
List<MyClass> myClassList = getList(MyClass[].class, jsonString);
...

public static final <T> List<T> getList(final Class<T[]> cl, final String json) {
    final T[] jsonToObject = new Gson().fromJson(json, cl);
    return Arrays.asList(jsonToObject);
}

Maven dependency

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.4</version>
    </dependency>
Lenar
  • 419
  • 4
  • 19