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.
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.
Below line,
String name = (String) jsonObject.get("enrollment_response");
should be
String name = jsonObject.getJSONObject("enrollment_response").getString("condition");
Value of enrollment_response is again a Json.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With