How to pretty print JSON string using 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.
Gson and Jackson are complete libraries offering JSON data-binding support for Java. Each are actively developed open-source projects. How to pretty print JSON using the Gson library in Java?
These are the steps we are going to perform:
- Create class
CrunchifyJsonGeneratorPrettyJSON.java
- Use JsonGenerator to create JSONObject in Java and store it at location /Users/appshah/Desktop/crunchifyJson.txt
- Read the Same JSON from file
- Print the simple JSON on Eclipse console
- Use
crunchifyPrettyJSONUtility()
utility to convert simple JSON to PrettyJSON – Convert JSON string to Pretty Print (Java, Gson) - Print the same PrettyJSON on console
Let’s enable Pretty Print of JSON with Jackson and GSON.
Convert JSON String to Pretty Print JSON output using Jackson. Gson – Pretty Print JSON.
package crunchify.com.tutorials; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import javax.json.Json; import javax.json.stream.JsonGenerator; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; /** * @author Crunchify.com * How to pretty print JSON in Java using Jackson and Gson both? Example attached. * */ public class CrunchifyJsonGeneratorPrettyJSON { public static void main(String[] args) { FileWriter writer = null; JSONParser parser = new JSONParser(); Object simpleObj = null; try { writer = new FileWriter("/Users/ashah/Downloads/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", "App Shah") .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/ashah/Downloads/crunchifyJson.txt")); } catch (IOException | ParseException e) { e.printStackTrace(); } if (simpleObj != null) { System.out.println("Simple JSON Result:\n" + simpleObj.toString()); } String prettyJson = null; if (simpleObj != null) { prettyJson = crunchifyPrettyJSONUtility(simpleObj.toString()); } System.out.println("\n======== Pretty JSON Result: ==========\n" + prettyJson); } // Prettify JSON Utility public static String crunchifyPrettyJSONUtility(String simpleJSON) { // parseString: Parses the specified JSON string into a parse tree JsonObject crunchifyJSON = JsonParser.parseString(simpleJSON).getAsJsonObject(); // JsonParser crunhifyParser = new JsonParser(); // JsonObject json = crunhifyParser.parse(simpleJSON).getAsJsonObject(); // Gson: This is the main class for using Gson. Gson is typically used by first constructing // a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it. // Gson instances are Thread-safe so you can reuse them freely across multiple threads. Gson prettyGson = new GsonBuilder().setPrettyPrinting().create(); // setPrettyPrinting(): Configures Gson to output Json that fits in a page for pretty printing. // This option only affects Json serialization. String prettyJson = prettyGson.toJson(crunchifyJSON); // toJson: Converts a tree of JsonElements into its equivalent JSON representation. 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.
In other words, it’s java api for json processing tutorial, java api for json processing maven, java api for json processing example and so on.
You need below two Maven Dependencies to make it work.
<dependency> <groupId>org.glassfish</groupId> <artifactId>javax.json</artifactId> <version>1.1.4</version> </dependency>
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.9.0</version> </dependency>
Here is a result:
Just run above program as a Java Application and you will see result as below. Here is an Eclipse Console Result.
Simple JSON Result: {"company":[{"address":"NYC, US","managedBy":"App Shah","support_for":"WordPress Plugins","name":"Crunchify","id":"24534-4324-6f3453-4234-w234234","team":"3","support":{"type":"wordpress","status":"active"}},{"address":"Mountain View, US","managedBy":"Larry Page,Sergey Brin","support_for":"gmail, drive, google+ and lot more","name":"Google","id":"3fwevwere-vwerfwevw-erw-vwe-efwfw","team":"46000","support":{"products":["Gmail","Google+","Drive","+ Lot More"],"status":"active"}}]} ======== Pretty JSON Result: ========== { "company": [ { "address": "NYC, US", "managedBy": "App Shah", "support_for": "WordPress Plugins", "name": "Crunchify", "id": "24534-4324-6f3453-4234-w234234", "team": "3", "support": { "type": "wordpress", "status": "active" } }, { "address": "Mountain View, US", "managedBy": "Larry Page,Sergey Brin", "support_for": "gmail, drive, google+ and lot more", "name": "Google", "id": "3fwevwere-vwerfwevw-erw-vwe-efwfw", "team": "46000", "support": { "products": [ "Gmail", "Google+", "Drive", "+ Lot More" ], "status": "active" } } ] } Process finished with exit code 0
Let us know if you face any issue running above code. We are more than happy to take a look at that.