Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java API for JSON Processing – Reading and Writing JSON objects

DZone's Guide to

Java API for JSON Processing – Reading and Writing JSON objects

· Java Zone
Free Resource

Managing a MongoDB deployment? Take a load off and live migrate to MongoDB Atlas, the official automated service, with little to no downtime.

In the previous article, we talked about how to form simple JSON array and objects. Now I want to mention how to transfer Json  objects and arrays into an I/O environment (this may be a file system or network environment) and how to convert an available JSON object or array in an I/O environment into JSON-P counterpart.

JsonReader and JsonWriter interfaces are being used in JSON-P, for read and write operations.

Example 1: Transferring of JSON object

JsonWriter objects are being created by createWriter(..) static method of Json class. Objects from OutputStream (Byte stream) or Writer (Character stream) family are accepted as method parameter.

// A simple array
JsonArray jsonArray = Json.createArrayBuilder()
   .add("Emin").add("Şahin").build();

//A simple object containing Json array
JsonObject jsonObject = Json.createObjectBuilder()
   .add("name", jsonArray)
   .add("surname", "Demir")
   .build();

  // PrintWriter and JsonWriter is being created
  // in try-with-resources
  try (PrintWriter pw = new PrintWriter("./src/main/resources/jsonObject.json")
     ;JsonWriter jsonWriter = Json.createWriter(pw)) {

  // Json object is being sent into file system
  jsonWriter.writeObject(jsonObject);

}

When the application is run;

{ ”name” : [" Emin " , " Şahin " ] ,” surname” : ” Demir “ } content is being created in jsonObject.json file.

The following set of code can be used if it is desired to read the content of json file saved as jsonObject.json and to create Json object model from this read data.

JsonReader reader =
   Json.createReader(new FileReader("./src/main/resources/jsonObject.json"));

   JsonObject obj = reader.readObject();

   System.out.println("Content: " + obj.toString());

Json outputs with JSON-P does not have pretty printing feature by default (No white space and alignment). It is an advantage in terms of file size but it is a reason that reduces readability of complex Json outputs. If a more readable output is desired, the following code can be changed entirely in try() { .. } expression.

// config Map is created for pretty printing.
Map<String, Boolean> config = new HashMap<>();

// Pretty printing feature is added.
config.put(JsonGenerator.PRETTY_PRINTING, true);

// PrintWriter and JsonWriter is being created
// in try-with-resources
try (PrintWriter pw = new PrintWriter("./src/main/resources/jsonObject.json")
    ;JsonWriter jsonWriter = Json.createWriterFactory(config).createWriter(pw)) {

   // Json object is being sent into file system
   jsonWriter.writeObject(jsonObject);

}

After this process, the output appears to be as follows.

{
    "name":[
        "Emin",
        "Şahin"
],
    "surname":"Demir"
}

Example 2: Consuming Json data returned from the Google Geocoding API

Reading and writing the Json data can also occur in a network environment as in file system. This example obtains geographic information about “Marmara University” from Google’s Geocoding API. Google Geocoding API can present output either XML or JSON format. After getting the Geographic information as JSON stream, JSON-P can consume streamed content and construct JSON-P data model in memory.

// Creating an URL object.
URL url = new URL("http://maps.googleapis.com/maps/api/geocode/json?address=Marmara+University&sensor=false");

// Retrieving byte stream object from URL source
InputStream is = url.openStream();

// Creating JSON object model from stream
JsonObject geoObj = Json
.createReader(is)
.readObject();

// PrintWriter and JsonWriter is being created
// in try-with-resources
try (PrintWriter pw = new PrintWriter("./src/main/resources/geoApi.json");
 JsonWriter jsonWriter = Json.createWriterFactory(config).createWriter(pw)) {

// Json object is being sent into file system
jsonWriter.writeObject(geoObj);
}

Examples can be found here. 

Hope to see you again..

MongoDB Atlas is the easiest way to run the fastest-growing database for modern applications — no installation, setup, or configuration required. Easily live migrate an existing workload or start with 512MB of storage for free.

Topics:
java ,json

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}