Quantcast
Channel: Crunchify
Viewing all articles
Browse latest Browse all 1037

Java JsonGenerator – JSON Processing API and How To Enable Pretty Print JSON Output (Gson + Jackson)

$
0
0

JsonGenerator and PreetyJSON output Java JsonGenerator   JSON Processing API and How To Enable Pretty Print JSON Output (Gson + Jackson)

This will be very interesting tutorial. Sometimes in your Enterprise Java Application, you have to deal with lots of JSON data. Sometimes you have Write to file, Read from file, log it properly in nice Pretty Format, etc.

Have you ever wondered about Pretty-Print JSON in Java? In this tutorial we will use javax.json package and JsonGenerator API to write JSONObject to file. Also we will use com.google.gson.Gson to prettify JSON Output.

These are the steps we are going to perform:

  1. Create class CrunchifyJsonGeneratorPrettyJSON.java
  2. Use JsonGenerator to create JSONObject in Java and store it at location /Users/<username>/Documents/crunchify/crunchifyJson.txt
  3. Read the Same JSON from file
  4. Print the simple JSON on Eclipse console
  5. Use crunchifyPrettyJSONUtility() utility to convert simple JSON to PrettyJSON – Convert JSON string to Pretty Print (Java, Gson)
  6. Print the same PrettyJSON on console

package crunchify.com.tutorials;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.json.Json;
import javax.json.stream.JsonGenerator;

import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * @author Crunchify.com
 * JsonGenerator and Pretty 
 */
public class CrunchifyJsonGeneratorPrettyJSON {

	public static void main(String[] args) {
		FileWriter writer = null;
		JSONParser parser = new JSONParser();
		Object simpleObj = null;

		try {
			writer = new FileWriter("/Users/<username>/Documents/crunchify/crunchifyJson.txt");
		} catch (IOException e) {
			e.printStackTrace();
		}

		// JsonGenerator to create JSONObject and store it to file location mentioned above
		JsonGenerator generator = Json.createGenerator(writer);
		 generator
         .writeStartObject().writeStartArray("company")
         	.writeStartObject()
         		.write("name", "Crunchify")
         		.write("managedBy", "Arpit")
         		.write("address", "NYC, US")
         		.writeStartObject("support")
         			.write("type", "wordpress")
         			.write("status", "active")
         		.writeEnd()
         		.write("support_for", "WordPress Plugins")
         		.write("id", "24534-4324-6f3453-4234-w234234")
         		.write("team", "3")
            .writeEnd()
         
         	.writeStartObject()
         		.write("name", "Google")
         		.write("managedBy", "Larry Page,Sergey Brin")
         		.write("address", "Mountain View, US")
         		.writeStartObject("support")
         			.writeStartArray("products")
         				.write("Gmail")
         				.write("Google+")
         				.write("Drive")
         				.write("+ Lot More")
         			.writeEnd()	
         			.write("status", "active")
         		
         		.writeEnd()
         		.write("support_for", "gmail, drive, google+ and lot more")
         		.write("id", "3fwevwere-vwerfwevw-erw-vwe-efwfw")
         		.write("team", "46000")
            .writeEnd()
         .writeEnd()
         .writeEnd();
		generator.close();

		try {
			simpleObj = parser.parse(new FileReader("/Users/<username>/Documents/crunchify/crunchifyJson.txt"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		System.out.println("Simple JSON Result:\n" + simpleObj.toString());
		
		String prettyJson = crunchifyPrettyJSONUtility(simpleObj.toString());
		System.out.println("\nPretty JSON Result:\n" + prettyJson);

	}

	// Prettify JSON Utility
	public static String crunchifyPrettyJSONUtility(String simpleJSON) {
		JsonParser crunhifyParser = new JsonParser();
		JsonObject json = crunhifyParser.parse(simpleJSON).getAsJsonObject();

		Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
		String prettyJson = prettyGson.toJson(json);

		return prettyJson;
	}
}

Interface JsonGenerator writes JSON data to an output source in a streaming way. The class Json contains methods to create generators for character or output streams.

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

You need below two Maven Dependencies to make it work.

<dependency>
	<groupId>org.codehaus.jackson</groupId>
	<artifactId>jackson-mapper-asl</artifactId>
	<version>1.9.13</version>
</dependency>

<dependency>
	<groupId>com.google.code.gson</groupId>
	<artifactId>gson</artifactId>
	<version>2.3</version>
</dependency>

Here is a result:

Simple JSON Result:
{"company":[{"id":"24534-4324-6f3453-4234-w234234","support":{"status":"active","type":"wordpress"},"address":"NYC, US","name":"Crunchify","managedBy":"Arpit","team":"3","support_for":"WordPress Plugins"},{"id":"3fwevwere-vwerfwevw-erw-vwe-efwfw","support":{"status":"active","products":["Gmail","Google+","Drive","+ Lot More"]},"address":"Mountain View, US","name":"Google","managedBy":"Larry Page,Sergey Brin","team":"46000","support_for":"gmail, drive, google+ and lot more"}]}

Pretty JSON Result:
{
  "company": [
    {
      "id": "24534-4324-6f3453-4234-w234234",
      "support": {
        "status": "active",
        "type": "wordpress"
      },
      "address": "NYC, US",
      "name": "Crunchify",
      "managedBy": "Arpit",
      "team": "3",
      "support_for": "WordPress Plugins"
    },
    {
      "id": "3fwevwere-vwerfwevw-erw-vwe-efwfw",
      "support": {
        "status": "active",
        "products": [
          "Gmail",
          "Google+",
          "Drive",
          "+ Lot More"
        ]
      },
      "address": "Mountain View, US",
      "name": "Google",
      "managedBy": "Larry Page,Sergey Brin",
      "team": "46000",
      "support_for": "gmail, drive, google+ and lot more"
    }
  ]
}

Have anything to add to this article? Please chime in and join the conversion.


The post Java JsonGenerator – JSON Processing API and How To Enable Pretty Print JSON Output (Gson + Jackson) appeared first on Crunchify.
Author: Arpit Shah


Viewing all articles
Browse latest Browse all 1037

Trending Articles