How to parse multidimensional json array in java
arrays, java, json
Solution
First of all: Do not use the JSON parsing library you're using. It's horrible. No, really, horrible. It's an old, crufty thing that lightly wraps a Java rawtype Hashmap. It can't even handle a JSON array as the root structure.
Use Jackson, Gson, or even the old json.org library.
That said, to fix your current code:
JSONObject enrollmentResponseObject =
(JSONObject) jsonObject.get("enrollment_response");
This gets the inner object. Now you can extract the inner fields:
String condition = (String) enrollmentResponseObject.get("condition");
And so forth. The whole library simply extends a `Hashmap` (without using generics) and makes you figure out and cast to the appropriate types.
Problem
I have a two dimensional JSON array object like below ``` {"enrollment_response":{"condition":"Good","extra":"Nothig","userid":"526398"}} ``` I would like to parse the above Json array object to get the condition, extra, userid.So i have used below code ``` JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader("D:\\document(2).json")); JSONObject jsonObject = (JSONObject) obj; String name = (String) jsonObject.get("enrollment_response"); System.out.println("Condition:" + name); String name1 = (String) jsonObject.get("extra"); System.out.println("extra: " + name1); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } ``` Its throwing an error as ``` "Exception in thread "main" java.lang.ClassCastException: org.json.simple.JSONObject cannot be cast to java.lang.String at com.jsonparser.apps.JsonParsing1.main(JsonParsing1.java:22)" ``` Please anyone help on this issue.