×

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array.

Json Array

Ordered lists of values are represented by JSON arrays. Multiple values can be stored in a JSON array. In a JSON array, you can store a string, a number, a boolean, or an object.Objects in a JSON array must be distinguished by commas.JSON array is represented by the [] (square bracket).

The below is a simple example for the Json array

{"employees":[    
    {"name":"Edmund", "place":"Rome", "age":23},    
    {"name":"Horatio", "place":"Iltaly", "age":28},  
    {"name":"Malacchai", "place":"Portland", "age":33},    
    {"name":"Aurora", "place":"England", "age":41}   
]}  

Java uses the org.json package to access and manipulate JSON data. JSON data can be encoded and decoded in Java using the org.json package. The org.json class provides a number of crucial classes that allow us to execute various actions on the JSON data. The main classes are

  • JSONObject
  • JSONValue
  • JSONArray
  • JSONNumber
  • JSONString

JSONObject

An irreversible JSON object variable (an apparently random collection of none or maybe more name/value pairs) is represented by the JsonObject class. The JSON object name/value conversions are also provided in an immutable map view.

Using JsonReader, a JsonObject instances can be produced from a source of input.

readObject().

JSONValue

An object, array, numeric, text, boolean (true or false), or null is an example of a JSON value. Except for objects and arrays, all values are linear. SQL considers a JSON result of null to be a value.

JSONArray

An irreversible JSON array is represented by sonArray (an ordered sequence of zero or more values). Additionally, it offers a static list view of the array's values.

Either applying an array constructor object or importing JSON data from an input source, a JsonArray object can be formed.

The example that follows shows how to use the JsonReader.readArray() function to build a JsonArray object from an input source.

JSONNumber

Deployments may locally record the numeric value in a BigDecimal object. The int, long, BigInteger, double, and String types are all able to create the BigDecimal object. The BigDecimal interpretations are used to define several of the procedure definitions in this class.

JSONString

Researchers most often use JSON (JavaScript Object Notation), a lightweight data-exchange format, for consumer interactions. It is both simple to read and write and merge.

How it Works

The following are the steps of how to iterate the JSON array in Java

  • Make a Maven installation and include a POM.xml file with a json dependency.
  • Create a JSON data string that you can manipulate by turning it into a JSON object.
  • Next, we use the getJSONArray() method to extract the JSON Array from the JSON Object and save it in a variable with the type JSONArray.
  • The array name is a string that is retrieved from the Object using the getJSONArray() function.
  • After that, a for loop from 0 to JSONArray is used.
  • The array's size is returned via the length() method.
  • Each index record is kept as a JSONObject. We utilise the getJSONObject() function of the JSONArray to retrieve the JSON object associated with a specific index.
  • By supplying the global variable as a string to the get() method of the JSONObject, we may retrieve the value of a specific field.

Let’s understand with an example program.

File Name: JSONArr.java

package javaTpoint.JSONExample;  
  
import java.io.FileWriter;  
import java.io.IOException;  
import org.json.simple.JSONArray;  
import org.json.simple.JSONObject;  
  
  public class JSONArr {  
      
       public static void main(String[] args) {  
          
          JSONObject jsonObject = new JSONObject();  
          
       jsonObject.put("name", "Manoj Tomar");  
        jsonObject.put("dept","Engineering");  
        jsonObject.put("branch", "C.S.E");  
        jsonObject.put("academic year", 3);  
          
        JSONArray list1 = new JSONArray();  
        list1.add("Ravi");  
        list1.add("Rajesh");  
        list1.add("Raashi");  
  
       jsonObject.put("Names", list1);  
          
        JSONArray list2 = new JSONArray();  
        list2.add("JAVA");  
        list2.add("CPP");  
        list2.add("DBMS");  
  
        jsonObject.put("Course", list2);  
          
        JSONArray list3 = new JSONArray();  
        list3.add("3");  
        list3.add("4");  
        list3.add("2");  
  
        jsonObject.put("Year", list3);  
          
       
        try (FileWriter file = new FileWriter("D:\\newfile.json")) {  
              
            file.write(jsonObject.toJSONString());  
            file.flush();  
  
        }  
        catch (IOException e) {  
            e.printStackTrace();  
        }  
          
      
        JSONArray jsonArray = (JSONArray) jsonObject.get("Names");  
          
          
    
        for (int i = 0; i < jsonArray.size(); i++) {  
              
            System.out.println(jsonArray.get(i));  
        }  
    }  
  
}  

Output

Ravi 
Rajesh
Raashi

Distinction with Array

A data structure called an array is used by most computer languages and holds a collection of variables in some kind of a predetermined sequence. An array data type exists in JSON.

The sample would involve a JSON data structure displaying the same content if the initial line and the semicolon at the end were removed. This is due to the fact that JSON is built on a portion of JavaScript, as Its already stated.


Related Topics

Java Integer parseInt() method

The parseInt() method of Java Integer class parses the CharSequence argument as a signed decimal integer. The second parameter parses the string argument as a signed integer in the radix specified...

2 minutes read.

Generics vs Wildcard in Java

In generic programming, the question mark (?) is often referred to as the wildcard. It stands for a mysterious type. The wildcard can be used for many different contexts, such as...

4 minutes read.

Java Type Casting

Type casting is a technique or process used in Java to convert one data type into another, either manually or automatically. The compiler performs the automatic conversion, and the programmer...

3 minutes read.

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level. If a node has no child nodes, it is said to...

3 minutes read.

Java Print Writer

PrintWriter: It is used to write output data from the file. It is the class of Java.io package. It inherits the properties of the Writer class. Writer Class: It is a class of...

4 minutes read.

Generic Linked List in Java

A linear data structure known as a Linked List stores values in nodes. As we already know, each node has two properties: its value and a link to the node...

6 minutes read.

Java Math random() Method

The random() method of Math class returns a double value with a positive sign, less than 1 and greater than or equal to 0.0. This method is properly synchronized with...

1 minute read.

Java Integer rotateLeft() method

The rotateLeft() method of Java Integer class returns the value obtained by rotating the  2’s complement binary representation of the given integer value left by the specified number of bits. Syntax public...

1 minute read.

Java Map Generic

Java arrays maintain an ordered collection of things, and the index can be used to access the data (an integer). Unlike HashMap, which stores data as a Key/Value pair. We...

3 minutes read.

Java Clone Array

We frequently need to copy an array to back up its original components. We have a few unique numbers and strings, including Armstrong numbers, palindrome numbers, and palindrome strings. To...

4 minutes read.

Trimorphic numbers in Java

Wondered what the Trimorphic number is!! In this article, you can learn about what a Trimorphic number is referred to as and how to find whether a number is trimorphic...

3 minutes read.

Various Operation on Queue using Linked List in Java

We keep track of front and rear pointers in a queue data structure. The head of the line points to the first item, and the back to the last. Rear is...

3 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of...

3 minutes read.

Two Decimal Places Java

When a double data type is used in Java before a variable, this indicates 15 digits after decimal point. However, there are situations when we only require 2 decimal places...

4 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

FizzBuzz Program in Java

FizzBuzz is a well-known children's game. This game helps children learn division. The FizzBuzz game is becoming a popular programming question, appearing frequently in Core Java interviews. This section will...

3 minutes read.