×

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

Properties Class in Java

Properties class is associated with Java since JDK 1.0, i.e. it is a legacy class. It is the subclass of Hashtable. It is used to maintain the lists of values in which...

5 minutes read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

Magnanimous Number in java

Magnanimous Number When the left and right halves of a majestic number are combined, the result is invariably a prime number, which must have at least two digits. The number's left...

3 minutes read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

How to Convert Hexadecimal to Decimal in Java

How to Convert Hexadecimal to Decimal in Java There are two methods to convert Hexadecimal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method It is a static method of...

2 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Java Integer toUnsignedLong() method

The toUnsignedLong() method of Java Integer class returns a long value by simply converting the given argument to long after an unsigned conversion. Syntax public static long toUnsignedLong (int  x) Parameters The parameter ‘x’...

1 minute read.

Comparetoignorecase in Java

In Java, the function compareToIgnoreCase ( ) is part of the String class, which is part of the java.lang package. It is used to compare any two strings while disregarding...

4 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Creating API Document Javadoc tool

The JavaDoc utility is a document generator tool written in Java that generates standard documentation in HTML format. It parses declarations and documentation in a source file collection that describes...

3 minutes read.

Difference between throw and throws in java

This article shows you the core difference between “throw” and “throws”keywords in Java programming language.The throw keyword tells Java you want another part of the code to deal withthe exception,...

2 minutes read.

Java Framework List

The framework is the programs which are written in Java. Frameworks in Java are used to create web applications. The code which can reuse can act as a reference for...

6 minutes read.

Java Password Generator

Generally, we must create a strong password for security reasons. In Java, there are numerous strategies for creating secure passwords. We will learn how to create a strong password in...

4 minutes read.

Java Integer toUnsignedString() method

The toUnsignedString() method of Java Integer class returns a string representation of the argument as an unsigned decimal value. The second syntax returns a string representation of the given argument as...

2 minutes read.