How to iterate or loop through JSON array in Java
In this tutorial, we will learn how to iterate a JSON array in Java with the code and Explanation using json-simple-1.1.1.jar.
What is a JSON array?
- It represents a list of ordered values.
- Stores several values separated with commas (,).
- It stores the number, string, boolean, or object.
- [] (square bracket) represents JSON Array.
Prerequisite
You have to download json-simple-1.1.1.jar Version 1.1.1 from here.
Click here to directly download json-simple-1.1.1.jar
After download, the json-simple-1.1.1.jar add the .jar file to your IDE. Example NetBeans, etc.
A simple JSON file as an example
Here we already have a Detail.json file that contains an array of names.
Detail.json
{ "Names": [ "Aman", "Namita", "Piyush", "Priyansh", "kartik", "Adarsh" ] }
Java program to iterate or loop through JSON array
import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class IterateJsonExample { public static void main(String[] args) { JSONParser jsonParserObj = new JSONParser(); try { JSONObject jsonObj = (JSONObject) jsonParserObj.parse(new FileReader("E://Detail.json")); System.out.println("Names are : "); JSONArray jsonArrObj = (JSONArray) jsonObj.get("Names"); Iterator<String> iteratorObj = jsonArrObj.iterator(); while (iteratorObj.hasNext()) { System.out.println(iteratorObj.next()); } } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } catch (ParseException ex) { ex.printStackTrace(); } } }
Output:
Names are : Aman Namita Piyush Priyansh kartik Adarsh
Explanation
- Line 13: Here we created an object named jsonParserObj of JSONParser class to read the JSON file.
- Line 15: In try block,we using the jsonParserObj.parse() method and the FileReader class we read the JSON file and store it in jsonObj of the JSONObject.
- Line 18: Using the jsonObj.get() method, we get our array of names and stores in the JSONArray object known as jsonArrObj.
- Line 20 – 23: By using the jsonArrObj.iterator() method we store the values of jsonArrObj and in a while loop using the iteratorObj.next() that returns the value and simply we print that values.
That’s enough for an overview of how to iterate or loop through JSON array.
How to access the particular name in this list