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

Just released, a free O’Reilly book on Reactive Microsystems: The Evolution of Microservices at Scale. Brought to you in partnership with Lightbend.

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..

Strategies and techniques for building scalable and resilient microservices to refactor a monolithic application step-by-step, a free O'Reilly book. Brought to you in partnership with Lightbend.

Topics:
java ,json

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}