What is json array in java

How to read/parse JSON array using Java?

A Json array is an ordered collection of values that are enclosed in square brackets i.e. it begins with ‘[’ and ends with ‘]’. The values in the arrays are separated by ‘,’ (comma).

Sample JSON array

The json-simple is a light weight library which is used to process JSON objects. Using this you can read or, write the contents of a JSON document using Java program.

JSON-Simple maven dependency

Following is the maven dependency for the JSON-simple library −

  com.googlecode.json-simple json-simple 1.1.1  

Paste this with in the tag at the end of your pom.xml file. (before tag)

Example

First of all, let us create a JSON document with name sample.json with the 6 key-value pairs and an array as shown below −

To read an array from a JSON file using a Java program −

JSONParser jsonParser = new JSONParser();
//Parsing the contents of the JSON file JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/players_data.json"));
String value = (String) jsonObject.get("key_name");
  • Just like other element retrieve the json array using the get() method into the JSONArray object.
JSONArray jsonArray = (JSONArray) jsonObject.get("contact");
  • The iterator() method of the JSONArray class returns an Iterator object using which you can iterate the contents of the current array.

//Iterating the contents of the array Iterator iterator = jsonArray.iterator(); while(iterator.hasNext())

Following Java program parses the above created sample.json file, reads its contents and, displays them.

Example

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 ReadingArrayFromJSON < public static void main(String args[]) < //Creating a JSONParser object JSONParser jsonParser = new JSONParser(); try < //Parsing the contents of the JSON file JSONObject jsonObject = (JSONObject) jsonParser.parse(new FileReader("E:/test.json")); //Forming URL System.out.println("Contents of the JSON are: "); System.out.println("ID: "+jsonObject.get("ID")); System.out.println("First name: "+jsonObject.get("First_Name")); System.out.println("Last name: "+jsonObject.get("Last_Name")); System.out.println("Date of birth: "+ jsonObject.get("Date_Of_Birth")); System.out.println("Place of birth: "+ jsonObject.get("Place_Of_Birth")); System.out.println("Salary: "+jsonObject.get("Salary")); //Retrieving the array JSONArray jsonArray = (JSONArray) jsonObject.get("contact"); System.out.println(""); System.out.println("Contact details: "); //Iterating the contents of the array Iteratoriterator = jsonArray.iterator(); while(iterator.hasNext()) < System.out.println(iterator.next()); >> catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >catch (ParseException e) < e.printStackTrace(); >> >

Output

Contents of the JSON are: ID: 1 First name: Krishna Kasyap Last name: Bhagavatula Date of birth: 1989-09-26 Place of birth: Vishakhapatnam Salary: 25000 Contact details: e-mail: krishna_kasyap@gmail.com phone: 9848022338 city: Hyderabad Area: Madapur State: Telangana

Источник

What is json array in java

JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array. A JsonArray object can be created by reading JSON data from an input source or it can be built from scratch using an array builder object. The following example demonstrates how to create a JsonArray object from an input source using the method JsonReader.readArray() :

 JsonReader jsonReader = Json.createReader(. ); JsonArray array = jsonReader.readArray(); jsonReader.close(); 

The following example demonstrates how to build an empty JSON array using the class JsonArrayBuilder :

 JsonArray array = Json.createArrayBuilder().build(); 
 JsonArray value = Json.createArrayBuilder() .add(Json.createObjectBuilder() .add("type", "home") .add("number", "212 555-1234")) .add(Json.createObjectBuilder() .add("type", "fax") .add("number", "646 555-4567")) .build(); 
 JsonArray arr = . ; JsonWriter writer = Json.createWriter(. ) writer.writeArray(arr); writer.close(); 

The values in a JsonArray can be of the following types: JsonObject , JsonArray , JsonString , JsonNumber , JsonValue.TRUE , JsonValue.FALSE , and JsonValue.NULL . JsonArray provides various accessor methods to access the values in an array. The following example shows how to obtain the home phone number «212 555-1234» from the array built in the previous example:

 JsonObject home = array.getJsonObject(0); String number = home.getString("number"); 

JsonArray instances are list objects that provide read-only access to the values in the JSON array. Any attempt to modify the list, whether directly or using its collection views, results in an UnsupportedOperationException .

Читайте также:  About jframe in java

Источник

Handling JSON Arrays in Java

Handling JSON Arrays in Java

  1. Handling JSON Arrays in Java
  2. JSON Objects and JSON Arrays in Java
  3. Use Java’s Built-in Libraries to Read a JSON Array in Java
  4. Conclusion

JSON is a popular and widely used data-interchange format among developers and organizations. The term JSON stands for JavaScript Object Notation.

It is a lightweight, readable, and text-based framework specially designed to facilitate data exchange in the human-readable format. JSON is an open standard format that means it can be used anywhere without special requirements.

Moreover, JSON is supported by most programming languages. You might have come across JSON if you ever worked as a project developer that requires data interchange.

For example, we often use JSON Objects to transfer data from a server to a mobile application and vice versa. This article will understand JSON basics, such as the structure of JSON, data types, JSON Objects, JSON Arrays, etc.

We will also understand how to work with JSON in Java. In the end, this article provides an example code to handle JSON in Java.

Handling JSON Arrays in Java

JSON is a very flexible and lightweight information-sharing framework where we use objects and datatypes to create and share information.

In JSON, data is represented as key-value pairs where the key is specifically a string, while the value can be any data type supported by JSON.

In addition to these basic JSON data types, we can also use JSON Arrays and JSON Objects as the value in a key-value pair.

Further, in the article, we will study more about arrays and objects. But before that, let’s look at the features of JSON.

  1. JSON is very simple. You don’t have to put any extra effort to understand and use JSON.
  2. JSON is easily understandable and self-describing. By looking at a JSON object, you can easily comprehend what it is intended to convey.
  3. JSON is language independent. This feature has proved to be a major factor in the wide acceptance of JSON. We can work with JSON in almost every language with the help of libraries and simple codes.
  4. JSON is faster than XML. It is yet another reason for using it widely.

JSON Objects and JSON Arrays in Java

Before we learn to use JSON objects and arrays in Java, we shall understand the JSON objects and JSON arrays.

Читайте также:  Min arg is an empty sequence python перевод

JSON objects are very similar to the dictionary data type, where the data is stored as key-value pairs. The key in this key-value pair should be a string, while the value can be an object, an array, or any other supported datatype.

We must separate a key and a value by a colon : and each key-value pair by a comma , . A JSON object is represented by using curly brackets <> .

We can make arbitrarily complex JSON objects by nesting objects and arrays into our JSON objects. It is called a hierarchical JSON object.

Here’s an example of a JSON object representing a student’s details.

"name": "Roger", "Roll": 22, "Class": "XI"> 

Note that we have quoted the string values with double-converted commas, while numbers do not need to be quoted.

We have just discussed JSON objects that are similar to a dictionary. On the other hand, JSON arrays are similar to lists.

We enclose objects in square brackets [] in a list. A JSON array can contain any supported data type, including another array or a JSON object.

Here is an example of a JSON array.

Note that the JSON array above contains a number, a string, and an object. It means we can store different data types in an array.

Use Java’s Built-in Libraries to Read a JSON Array in Java

Java is a powerful language with a large number of libraries. Luckily, we have built-in libraries to read JSON objects and arrays in Java.

Such libraries facilitate our work and make it simple to parse and read JSON objects and arrays. Further in this article, we will learn to use such libraries in code to read the JSON object and JSON array in Java.

Before proceeding to the code, we create a JSON object and store it in a file. Note that a JSON file has the extension .json .

So if you want to test and execute the code, copy and paste the following JSON code and save the file with the .json extension at any desired location. The JSON code is given below.

[  "name":"MMN",  "roll": 24,  "marks": [91, 95, 97, 97, 94],  "parents":   "name": "IMT",  "mobile":"1234567890"  >,  "hobbies": ["sports", "reading", "music"],  "others": ["A", 1] >] 

You should note that this JSON file contains a JSON Array with a single JSON Object. This inner JSON Object then contains several key-value pairs with different data types.

For example, name is a string, roll is an integer (note that JSON stores integers as long integers), marks is a JSON Array, parents is another JSON Object, and so on. Therefore, this is an example of arbitrarily complex JSON data.

Let us understand how we can read such a JSON Object using Java.

Before writing the code, you must make sure that you have downloaded the JSON jar file and added the classpath variable pointing to that JSON file. If you do not do this, JSON will not be compiled.

We can open a JSON file the same way as we open any other file in Java, essentially by using the File() constructor.

We must surround the file opening statement with a try-catch block to handle the necessary exception that the constructor throws.

Once the file is open, its object is passed to the FileReader() constructor.

We use a JSON parser that returns a Java Object to parse the JSON content. We should use an explicit cast to cast a JSON Array.

Our JSON Array contains a single object, but in some cases, we might have multiple JSON Objects in a JSON Array, so we should traverse the parsed array using a loop. We extract each JSON Object from the parsed JSON Array and further process it.

Note that we should know the JSON Object structure that we are iterating because we need to extract the values in a JSON Object using the key.

Further, we extract the data from the JSON Object by passing it to a function that uses named keys. Since JSON Object contains different data types, each can be handled accordingly.

For example, we displayed the integer, string, and array but iterated the nested JSON Object parents . The following code implements the logic explained.

import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.*;  import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException;  public class JSONReader   public static void main(String [] args)    JSONParser parser = new JSONParser();  FileReader fileReader;  try   File file = new File("/home/stark/eclipse-workspace-java/Aditya/src/data.json");  fileReader = new FileReader(file);  // Parser returns an object, we need an explicit cast to covert it into a JSONArray  JSONArray array = (JSONArray) parser.parse(fileReader);   //Traverse the list  for(int i=0;iarray.size();i++)    JSONObject obj = (JSONObject)array.get(i);  parseObject(obj);  >   >   catch(FileNotFoundException e)    System.out.println(e.getStackTrace()+ " :File Not Found");  >  catch(ParseException e)    System.out.println(e.getStackTrace()+ " :Could not parse");  >  catch(IOException e)    System.out.println(e.getStackTrace()+ " :IOException");  >  >   private static void parseObject(JSONObject obj)   String name = (String)obj.get("name");  long roll = (long)obj.get("roll");  JSONArray marks = (JSONArray)obj.get("marks");  JSONArray hobbies = (JSONArray)obj.get("hobbies");  JSONObject parents = (JSONObject)obj.get("parents");  JSONArray others = (JSONArray)obj.get("others");   System.out.println("Name: "+name);  System.out.println("Roll: "+roll);  System.out.println("Marks: "+marks);  System.out.println("Hobbies: "+hobbies);  System.out.println("Parent's Name: "+parents.get("name")+", Mobile: "+parents.get("mobile"));  System.out.println("Others: "+others);  > > 

You should specify the correct path of the file in the File() constructor. The output of the code above is below.

Name: MMN Roll: 24 Marks: [91,95,97,97,94] Hobbies: ["sports","reading","music"] Parent's Name: IMT, Mobile: 1234567890 Others: ["A",1] 

Conclusion

Java is a popular programming language, and often we come across situations where we need data interchange. Although other data interchange formats exist, JSON is one of the most popular, easy, and understandable formats.

We have learned JSON format, its datatypes, and parsed JSON files in Java. JSON can have an arbitrarily complex structure that enables us to interchange any JSON data.

On the other hand, Java provides a simple, unique yet powerful method to handle the JSON.

Related Article — Java JSON

Источник

Оцените статью