Java JSON Processing (JSON-P) with Example


Introduction

Java programs can operate with JSON data due to the strong Java JSON Processing (JSON-P) API. Web servers and clients frequently exchange data using the lightweight JSON data transfer standard. JSON-P offers the Object Model API and the Streaming API as its two primary methods for processing JSON data.

Let us talk about these two strategies and use examples to show how they work and what they can do. We hope that our readers will learn about the Object Model API and Streaming API, together with Programming examples, by understanding this article's explanations on Java JSON Processing (JSON-P) with example.

Features of Java JSON Processing (JSON-P)

We know that JSON-P provide us with two different features to process JSON data −

  • Object Model API − This method shows JSON data as a structure made up of objects, arrays, and values, much like a tree. It is comparable to XML's DOM parser. The Object Model API makes it simple to navigate and modify JSON parts while managing tiny JSON data.

  • Streaming API − The Streaming API processes JSON data sequentially rather than putting the complete JSON into memory, making it a more memory-efficient method. It is suitable for handling massive JSON data and is comparable to using the StAX parser for XML.

Read and Parse JSON Data with Object Model API

In this programming example we will learn how to Read and Parse JSON Data with Object Model API.

Example

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public class ModObjtest 
{
   public static void main(String args []) throws IOException 
   {
      try (InputStream fis = new FileInputStream("data.json");
      JsonReader jsonReader = Json.createReader(fis))
      {
         JsonObject jsonObject = jsonReader.readObject();
         // Step 4: fetch data from the JsonObject 
         String name = jsonObject.getString("name");
         int age = jsonObject.getInt("age");
         boolean isMarried = jsonObject.getBoolean("isMarried");
         // print data
         System.out.println("Name: " + name);
         System.out.println("Age: " + age);
         System.out.println("Married: " + isMarried);
      }
   }
}

Output

** data.json output**
{
   "name": "Sheli Sharma",
   "age": 28,
   "isMarried": true
}
** ModObjtest.java output**
Name: Sheli Sharma
Age: 28
Married: true

For this we have imported some important packages in this program.

javax.json.Json;
javax.json.JsonObject;
javax.json.JsonReader;
java.io.FileInputStream;
java.io.IOException;
java.io.InputStream;

After that we have defined a class named ModObjTest and inside the class we have called the main () function. Inside the main function we have throws the IOException and Open an input stream to read the JSON data from a file.

try (InputStream fis = new FileInputStream("data.json");

After that we have Created a JsonReader to read the JSON data by creating the object namedjsonReader of the class jsonReader and call the function named readObject ().

JsonReader jsonReader = Json.createReader(fis)) {

Now we have Parsed the JSON data into a JsonObject by creating the object namedjsonObject of the class named jsonObject and call the function named readobject ().

JsonObject jsonObject = jsonReader.readObject();

Now we have fetched data from the JsonObject by deaclaring a string named “name” and call the function named getString () and pass the value of “name” as an argument inside the parenthesis of the function.

String name = jsonObject.getString("name");

Now we have declared another variable named “age” which is integer type and call another function named getInt() and pass the value of the “age” inside the parenthesis of the function as an argument.

int age = jsonObject.getInt("age");

Now we have called another function named getBoolean () andf pass the value “isMarried” inside the parenthesis of the function as an argument and store the value to another variable named “ismarried” which is Boolean type.

boolean isMarried = jsonObject.getBoolean("isMarried");

Now we have printed all the data to get the desired output.

System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Married: " + isMarried);

Generate JSON Data with JSON-P Streaming API

In this particular programming example, we will know how to Generate JSON Data with JSON-P Streaming API.

Example

import javax.json.Json;
import javax.json.JsonObject;
import javax.json.stream.JsonGenerator;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class StreamJsontest
{
   public static void main(String args []) throws IOException 
   {
      try (OutputStream fos = new FileOutputStream("output.json");
      JsonGenerator jsonGenerator = Json.createGenerator(fos)) 
      {
         // Generate JSON data using the Streaming API
         jsonGenerator.writeStartObject()
            .write("name", "Aishee")
            .write("age", 25)
            .write("isStudent", true)
            .writeStartObject("indianName")
            .write("firstName", "Aarav")
            .write("lastName", "Sharma")
            .writeEnd()
            .writeStartObject("indianAddress")
            .write("homeNo", "325")
            .write("street", "SY Avenue")
            .write("hometown", "Kolkata")
            .write("state", "WB")
            .write("pin", "400001")
            .writeEnd()
            .writeEnd();
         // Close the JSON generator
         jsonGenerator.close();
      }s
      // Read JSON data from the file and convert it to a string
      String jsonString = readJsonFromFile("output.json");
      System.out.println(jsonString);
   }
   private static String readJsonFromFile(String file) throws IOException 
   {
      try (InputStream fis = new FileInputStream(file);
      JsonReader jsonReader = Json.createReader(fis)) {
         JsonObject jsonObject = jsonReader.readObject();
         return jsonObject.toString();
      }
   }
}

Output

{"name":"Aishee","age":25,"isStudent":true,
"indianName":{"firstName":"Aarav","lastName":"Sharma"},
"indianAddress":{"homeNo":"325","street":"SY Avenue",
"hometown":"Kolkata","state":"WB","pin":"400001"}}

To do this at first, we have imported some important packages in this program.

javax.json.Json;
javax.json.JsonObject;
javax.json.JsonReader;
java.io.FileInputStream;
java.io.IOException;
java.io.InputStream;

Now we have defined a class named StreamJsonTest and inside the function we have called the main () function which throws IOException. Inside the main () function we have Generated JSON data using the Streaming API by calling a function named writeStarObject().

jsonGenerator.writeStartObject()

Now we have closed the json generator by calling another function named json.genearator.

jsonGenerator.close();

After that we have Read JSON data from the file and convert it to a string by calling one more important function named readJsonFromFile () and print the json string.

String jsonString = readJsonFromFile("output.json");
System.out.println(jsonString);

Now we have thrown another important throws IOException and create the jsonReadObject to the class named jsonReadObject and calling another function named createReader ().

JsonReader jsonReader = Json.createReader(fis))

Lastly we have returned the jsonObject.toString ().

Conclusion

In this article we covered up all the main topic of JSON processing in java. It is very crucial topic of java regarding present scenario of IT software development industry. The value of Json processing in java is priceless. So we were tried our best to cover up all the aspect of this topic with logistic programming example and their explanation.

Updated on: 04-Oct-2023

91 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements