-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?

R_GAIT
  • 1
  • 1
  • 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. – Boann Nov 17 '15 at 17:09
  • Typo, added the correct JSON response. – R_GAIT Nov 17 '15 at 18:50
  • It's still invalid because there are key-value pairs in the `locations` array. – Boann Nov 17 '15 at 20:33

1 Answers1

-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");
ThomasThiebaud
  • 11,331
  • 6
  • 54
  • 77
  • 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? – R_GAIT Nov 19 '15 at 12:07
  • Yes it does. But my code was wrong. I updated my answer. – ThomasThiebaud Nov 19 '15 at 12:11