You can format JSON String in Java using Jackson API's pretty print feature. As you might have noticed in my previous JSON tutorials that the output of the programs is not properly formatted, which makes them hard to read, especially in large log files where there are so many other texts, both JSON and normal text is there. That's why it's advised to print JSON String properly formatted because then it will stand out in log file or console. Whenever we print JSON String from Java Programs by using method writeValueAsString(), it usually comes in one line, as shown in the following example :
This is not very readable as you cannot see how many attributes are there, what is their name and value, compare it to following formatted output which is printed using Jackson's pretty print feature:
It's way better than earlier output, it's much more readable. You can easily identify which one is the just simple name-value pair, which one is JSON array, and much more. Wondering, how to nicely print JSON String, just check out the example shown in the next section.
JAR files
C:\.m2\repository\org\codehaus\jackson\jackson-xc\1.9.12\jackson-xc-1.9.12.jar
C:\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.12\jackson-core-asl-1.9.12.jar
C:\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.12\jackson-mapper-asl-1.9.12.jar
That's all on how to format JSON String in Java using Jackson API's pretty print facility. This example is very useful while printing JSON in log files to differentiate it from other String outputs. Formatted output not only stands out in logs but also they are easier to read but there is one drawback also. You cannot grep them in one line, you need to use the grep command with a context option to grep a couple of lines around matching to see full JSON output.
If you like this tutorial and want to learn more about how to deal with JSON in Java, please check out the following amazing Java JSON tutorials :
{"name":"Virat","sport":"cricket","age":25,"id":121," lastScores":[77,72,23,57,54,36,74,17]}
This is not very readable as you cannot see how many attributes are there, what is their name and value, compare it to following formatted output which is printed using Jackson's pretty print feature:
{ "name" : "Virat", "sport" : "cricket", "age" : 25, "id" : 121, "lastScores" : [ 77, 72, 23, 57, 54, 36, 74, 17 ] }
It's way better than earlier output, it's much more readable. You can easily identify which one is the just simple name-value pair, which one is JSON array, and much more. Wondering, how to nicely print JSON String, just check out the example shown in the next section.
JSON String Format and Pretty Print Example
In this example, you will learn how to format the JSON String using Jackson's Pretty Print feature. It's easy to format JSON text, all you need to do is instead of just calling writeValueAsString() you need to first get defaultPrettyPrintWrite and then call writeValueAsString() method on that object. This will ensure that your JSON data will be nicely printed on console or log file i.e. wherever you print it.import java.io.IOException; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; /** * Java program to format JSON String using Jackson API. Jackson provides * nice pretty print feature to print JSON text as formatted output. * * @author Javin Paul */ public class JSONPrintDemo{ public static void main(String args[]) { int[] recentScores = {77, 72, 23, 57, 54, 36, 74, 17}; Player cricketer = new Player("Virat", "cricket", 25, 121, recentScores); ObjectMapper mapper = new ObjectMapper(); try { System.out.println("Default JSON String:" + mapper.writeValueAsString(cricketer)); System.out.println("formatted JSON String \n" + mapper.defaultPrettyPrintingWriter().writeValueAsString(cricketer)); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } class Player { private String name; private String sport; private int age; private int id; private int[] lastScores; public Player(String name, String sport, int age, int id, int[] lastinnings) { this.name = name; this.sport = sport; this.age = age; this.id = id; lastScores = lastinnings; } public final String getName() { return name; } public final String getSport() { return sport; } public final int getAge() { return age; } public final int getId() { return id; } public final int[] getLastScores() { return lastScores; } public final void setName(String name) { this.name = name; } public final void setSport(String sport) { this.sport = sport; } public final void setAge(int age) { this.age = age; } public final void setId(int id) { this.id = id; } public final void setLastScores(int[] lastScores) { this.lastScores = lastScores; } @Override public String toString() { return "Player [name=" + name + ", sport=" + sport + ", age=" + age + ", id=" + id + "]"; } } Output Default JSON String:{"name":"Virat","sport":"cricket","age":25, "id":121,"lastScores":[77,72,23,57,54,36,74,17]} formatted JSON String { "name" : "Virat", "sport" : "cricket", "age" : 25, "id" : 121, "lastScores" : [ 77, 72, 23, 57, 54, 36, 74, 17 ] }
Maven Dependency and JAR Files for Jackson
Since Jackson library is not part of core Java, you need to either specify Maven dependency in pom.xml file or you need to manually download those Jackson JAR files and put in your application's classpath.<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-xc</artifactId> <version>1.9.12</version> </dependency>
JAR files
C:\.m2\repository\org\codehaus\jackson\jackson-xc\1.9.12\jackson-xc-1.9.12.jar
C:\.m2\repository\org\codehaus\jackson\jackson-core-asl\1.9.12\jackson-core-asl-1.9.12.jar
C:\.m2\repository\org\codehaus\jackson\jackson-mapper-asl\1.9.12\jackson-mapper-asl-1.9.12.jar
That's all on how to format JSON String in Java using Jackson API's pretty print facility. This example is very useful while printing JSON in log files to differentiate it from other String outputs. Formatted output not only stands out in logs but also they are easier to read but there is one drawback also. You cannot grep them in one line, you need to use the grep command with a context option to grep a couple of lines around matching to see full JSON output.
If you like this tutorial and want to learn more about how to deal with JSON in Java, please check out the following amazing Java JSON tutorials :
- How to parse large JSON documents in Java? (code example)
- How to read JSON String using the json-simple library? (code example)
- How to convert JSON String to Java Object for example? (solution)
- How to convert a JSON array to String Array in Java? (solution)
- 3 Ways to parse JSON String in Java? (tutorial)
- How to use Google Protocol Buffer in Java? (tutorial)
- How to use Gson to convert JSON to Java Object? (example)
Many thanks indeed.
ReplyDeleteAccording to the API doc, since 1.9, the ObjectMapper.defaultPrettyPrintingWriter() method is deprecated. We should use ObjectMapper.writerWithDefaultPrettyPrinter() instead.
You can also pretty print JSON using Gson library, simpler and easier :
ReplyDeleteGson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(jsonObject);
System.out.println(jsonString);
can i get the code for jason object
ReplyDelete"a[i]":"j"
"a[0]":"1",
"a[1]":"2",
the values has to be increasing
you can using fastjson as well
ReplyDeleteSystem.out.println("FastJson start1");
User userDemo = new User(1, "2json", "2json", 30);
String jsonUser = JSON.toJSONString(userDemo);
System.out.println(jsonUser);
json format online https://www.2json.net/json/