JSON is widely used in web development as data exchange format because of its light weight nature.By default JSON is plain string however JSON looks scary if it is not formatted and in may situation formatted JSON is need for debugging.Here we will see how to format or how to enable pretty printing of JSON in java. If you are using Gson and Jackson then it is very easy to generate pretty print of JSON.
Here we have created a map(object of JSON) and added a list (array of JSON) as part of it. Whne we execute JSON is pretty printed. Similarly , we can have any POJO(Plain old java object) in-place of map and outcome is pretty printed.
Here we have multiple option to convert String/Object into pretty print format. In option 1, we created mapper instance of ObjectMapper and mapper instance have readValue method that read input(FIle, InputStream,String or Object) and with writeValueAsString() method it displays formatted output.Please note difference mentioned for 1.x and 2.x. Do not use defaultPrettyPrintingWriter() ,it has been deprecated instead prefer to use Option 2. In second option, we enable properties in mapper for "INDENT_OUTPUT", so by default if object is printed it will be pretty printed.
Read also:
How to convert JSON to Object and Object to JSON using Google Gson.
JSON Pretty printing using Gson:-
Gson has GsonBuilder has instance variable prettyPrinting(Boolean), while creating instance of GsonBuilder using create() method, if prettyPrinting is set true(using setPrettyPrinting() method ) then pretty printing will be enabled and JSON generated will be formatted. Download Gson jar from here and create a java file with following code lines.
Hide code lines
package com.GsonSampleProject.model;
|
JSON Pretty printing using Jackson:-
Download jackson-all-1.9.0.jar. Create a java class and use following code lines.
Hide code lines
package com.GsonSampleProject.model;
|
Read also:
How to convert JSON to Object and Object to JSON using Google Gson.
Tags:
JSON and XML
Thanks for sharing this great article and i want to read some informative article about Informatica Read Json.
ReplyDeleteAivivu chuyên vé máy bay, tham khảo
ReplyDeletevé máy bay đi Mỹ giá rẻ
vé máy bay từ mỹ về việt nam mùa dịch
đặt vé máy bay từ nhật về việt nam
mua vé máy bay từ đức về việt nam
vé máy bay từ canada về việt nam bao nhiêu tiền
giá vé máy bay hàn quốc về việt nam
khách sạn cách ly tại hà nội