tags:

views:

1691

answers:

5

hey,

i'm just getting started with using json with java. i'm not sure how to access string values within a JSONArray. for instance, my json looks like this:

    {
  "locations": {
    "record": [
      {
        "id": 8817,
        "loc": "NEW YORK CITY"
      },
      {
        "id": 2873,
        "loc": "UNITED STATES"
      },
      {
        "id": 1501,
        "loc": "NEW YORK STATE"
      }
    ]
  }

my code:

JSONObject req = new JSONObject(join(loadStrings(data.json),""));

JSONObject  locs     = req.getJSONObject("locations");

JSONArray  recs     = locs.getJSONArray("record");

i have access to the "record" JSONArray at this point, but am unsure as to how i'd get the "id" and "loc" values within a for loop. sorry if this isn't description isn't too clear, i'm a bit new to programming.

A: 

iterate over "recs" and get a JSONObject each time. Then take that reference and call getLong, getString or the data type you want.

Jorge
+5  A: 

Have you tried using JSONArray.getJSONObject(int), and JSONArray.length() to create your for-loop:

for (int i = 0; i < recs.length(); ++i) {
    JSONObject rec = recs.getJSONObject(i);
    int id = rec.getInt("id");
    String loc = rec.getString("loc");
    // ...
}
notnoop
ah, that makes sense. thanks for the example!cheers
minimalpop
A: 

Just guessing, but it looks like you're using the old Java implementation from json.org. There are several better and easier solutions nowaday so in the longer run it could be a good idea to have a look at newer alternatives.

Have a look at this article here on SO, I have used the Jackson library a couple of times, and like it a lot.

fvu
A: 

By looking at your code, I sense you are using JSONLIB. If that was the case, look at the following snippet to convert json array to java array..

 JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );  
 JsonConfig jsonConfig = new JsonConfig();  
 jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );  
 jsonConfig.setRootClass( Integer.TYPE );  
 int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );
Teja Kantamneni
A: 

Here's how I process elements in a JSONArray:

    JSONArray lineItems = jsonObject.getJSONArray("lineItems");
    for (Object o : lineItems) {
        JSONObject jsonLineItem = (JSONObject) o;
        String key = jsonLineItem.getString("key");
        String value = jsonLineItem.getString("value");
        ...
    }

Works great... :)

Piko