134

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 description isn't too clear, I'm a bit new to programming.

Michael Allan Jackson
  • 4,217
  • 3
  • 35
  • 45
minimalpop
  • 6,997
  • 13
  • 68
  • 80
  • 2
    Another thing (probably you found it)- you have missed a comma after third id value. It's good to always use some parser, for example http://json.parser.online.fr/ – Krystian Mar 15 '16 at 14:08

6 Answers6

239

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");
    // ...
}
idewz
  • 5
  • 1
  • 5
notnoop
  • 58,763
  • 21
  • 123
  • 144
  • I don't get this. If we can get `id` with a sinple `getInt` like how we get the value of a hashmap by specifying the key, then why do we have to iterate with a for loop? Doesn't iteration with the loop make the `id` get assigned to `int id` multiple times? – Nav Jun 28 '16 at 10:04
  • For more complex JSON found this nice solution per https://examples.javacodegeeks.com/core-java/json/java-json-parser-example/ – vikramvi Jun 29 '16 at 14:47
  • How would this work if I know the ID but need the matching loc? – ToofanHasArrived Mar 05 '19 at 23:45
  • 1
    Both of these links are broken – Keverly Sep 19 '22 at 15:48
5

An org.json.JSONArray is not iterable.
Here's how I process elements in a net.sf.json.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... :)

Michael Allan Jackson
  • 4,217
  • 3
  • 35
  • 45
Piko
  • 4,132
  • 2
  • 21
  • 13
4

Java 8 is in the market after almost 2 decades, following is the way to iterate org.json.JSONArray with java8 Stream API.

import org.json.JSONArray;
import org.json.JSONObject;

@Test
public void access_org_JsonArray() {
    //Given: array
    JSONArray jsonArray = new JSONArray(Arrays.asList(new JSONObject(
                    new HashMap() {{
                        put("a", 100);
                        put("b", 200);
                    }}
            ),
            new JSONObject(
                    new HashMap() {{
                        put("a", 300);
                        put("b", 400);
                    }}
            )));

    //Then: convert to List<JSONObject>
    List<JSONObject> jsonItems = IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .collect(Collectors.toList());

    // you can access the array elements now
    jsonItems.forEach(arrayElement -> System.out.println(arrayElement.get("a")));
    // prints 100, 300
}

If the iteration is only one time, (no need to .collect)

    IntStream.range(0, jsonArray.length())
            .mapToObj(index -> (JSONObject) jsonArray.get(index))
            .forEach(item -> {
               System.out.println(item);
            });
prayagupa
  • 30,204
  • 14
  • 155
  • 192
  • 1
    `.mapToObj` shows "unhandled exception: JSONException" – Andrejs Nov 09 '17 at 20:22
  • 1
    in syntax `.mapToObj(index -> (JSONObject) array.get(index))`, theres `jsonArray.get(index)` which potentially can throw `JSONException` but `JSONException extends RuntimeException` so it should fine at least at compile time – prayagupa Nov 11 '17 at 07:05
2

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 );  
skaffman
  • 398,947
  • 96
  • 818
  • 769
Teja Kantamneni
  • 17,402
  • 12
  • 56
  • 86
0

In case it helps someone else, I was able to convert to an array by doing something like this,

JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()

...or you should be able to get the length

((JSONArray) myJsonArray).toArray().length
wired00
  • 13,930
  • 7
  • 70
  • 73
  • `org.json.JSONObject` has a `toJSONArray(JSONArray names)` method and `org.json.JSONArray` has a `toJSONObject(JSONArray names)` method but it does not have a `toArray()` method. – BrionS Mar 10 '17 at 20:14
-2

HashMap regs = (HashMap) parser.parse(stringjson);

(String)((HashMap)regs.get("firstlevelkey")).get("secondlevelkey");

roger
  • 1
  • 1
  • 1
    A bit more clarification why your answer is better then the current accepted one would help understanding your solution. – Vad1mo Nov 02 '17 at 00:11