How to Prettify - Format - Beautify json in Java?
UPDATED: 22 October 2015
Tags:
JSON
Lately
I was working on web services of different websites. All of them gives response
in either JSONObject or JSONArray. Reading JSON in eclipse console is pretty
hard so searched over internet and found library called jackson-all.
Download library: http://www.java2s.com/Code/Jar/j/Downloadjacksonall190jar.htm
Source code
Output
Download library: http://www.java2s.com/Code/Jar/j/Downloadjacksonall190jar.htm
Source code
import java.io.IOException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.ObjectWriter; /** * Example of formating raw JSON * @author Vicky Thakor */ public class PrettifyJSONExample { public static void main(String[] args) { try { String json = "{\"candidate\" : \"Vicky Thakor\", \"expertise\" : [\"Core Java\", \"J2EE\", \"Design Pattern\"]}"; System.out.println("Unformatter json:" + json); /* Create required objects */ ObjectMapper objectMapper = new ObjectMapper(); Object object = objectMapper.readValue(json, Object.class); ObjectWriter objectWriter = objectMapper.writer().withDefaultPrettyPrinter(); /* Get the formatted json */ String formattedJSON = objectWriter.writeValueAsString(object); System.out.println("Formatter json:\n"+formattedJSON); } catch (IOException ex) { ex.printStackTrace(); } } }
Output
Unformatter json:{"candidate" : "Vicky Thakor", "expertise" : ["Core Java", "J2EE", "Design Pattern"]} Formatter json: { "candidate" : "Vicky Thakor", "expertise" : [ "Core Java", "J2EE", "Design Pattern" ] }
Tags:
JSON
0 comments :