Search code examples
javajsonkeyjson-simple

java/jsonsimple - use key to get value from a jsonarray


I have the following example json output form java/jsonsimple.

The JSONArray is:

[{"dd1":{"actionType":"Dept","collegeID":""}},{"dd2":{"actionType":"Dept","collegeID":""}}] 

I'm trying to figure out how to get the value for the "dd1" key by using the "dd1" instead of the ndx.

basically, I want to be able to test for a given "key" to see if it's in the array, with a value.

The docs for JSONArray, allow for foo.get(1), but not foo.get("dd1")

thanks

ps.

I tried to use the insert the above into a JSONObject, and then do a foo.get("dd1") but I didn't get the value.

The issue appears to come down to figuring out how to get dict that's in the [] array.

doing something like foo.get(1).get("dd1") doesn't work...

thanks


Solution

  • You have an array wrapping your dictionary in your JSON input, so you'd have to get the dictionary first, something like:

    foo.get(1).get("dd1");
    

    But you can change your JSON to be a simple dictionary, like this:

    {
       "dd1": {"actionType":"Dept","collegeID":""},
       "dd2": {"actionType":"Dept","collegeID":""}
    }
    

    And then you'll be able to do:

    foo.get("dd1");