简体   繁体   中英

How to parse multidimensional json array in java

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.

This works, but trust me: change library.

JSONObject jsonObject = (JSONObject) obj;

JSONObject name = (JSONObject) jsonObject.get("enrollment_response");
System.out.println("Condition:" + name);

String name1 = (String) name.get("extra");
System.out.println("extra: " + name1);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM