-4

Trying to use json simple to parse data from rest service. The response looks like:

{
   "locations": [
      "city" : "San Jose",
      "state" : "Ca",
    "job" : {
      "site" : "Main Processing",
      "region" : "USA"
    }
  ]
}
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);

JSONArray array = (JSONArray) jsonObject.get("locations");

for(int i = 0; i < array.size(); i++) {
 String site = array.getJSONObject(i).getString("site");
}

My issue is I am having trouble getting a reference to the job element from JSONArray object. The "locations" reference is basic parsing but the "job" reference is giving me issue when its defined inside an array.

Also getJSONObject does not seem to be a valid method to JSONArray.

Can this be done with the json-simple library?

3
  • Your example data as shown is completely invalid. The JSON spec doesn't allow unquoted string keys, or for key-value pairs as members of arrays, or for the omission of commas between the key-value pairs. Commented Nov 17, 2015 at 17:09
  • Typo, added the correct JSON response. Commented Nov 17, 2015 at 18:50
  • It's still invalid because there are key-value pairs in the locations array. Commented Nov 17, 2015 at 20:33

1 Answer 1

-1

The getJSONObject method is provided by the org.json.JSONArray class. (without using json-simple). I can not find it in the json-simple doc. So using the org.json.* package import, you can do:

JSONObject jsonObject = new JSONObject(jsonAsString);
JSONArray array = jsonObject.getJSONArray("locations");

//You should check that array.length() >= 3
JSONObject job = array.getJSONObject(2);
String site = job.getString("site");
Sign up to request clarification or add additional context in comments.

2 Comments

This not able to get the "site" tag data. Getting an error basically said element does not exist. Are there json libraries that specifically address nested objects?
Yes it does. But my code was wrong. I updated my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.