Java JsonGenerator – JSON Processing API and How

05:45:00 , , 0 Comments

JsonGenerator and PreetyJSON output
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
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.

Here is a result:

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

0 comments :