Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse multidimensional json array in java

Tags:

java

json

arrays

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.

like image 315
Test1234 Avatar asked Feb 18 '14 09:02

Test1234


2 Answers

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.

like image 109
Brian Roach Avatar answered Oct 12 '22 09:10

Brian Roach


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.

like image 37
Shashank Kadne Avatar answered Oct 12 '22 11:10

Shashank Kadne