Thursday, February 28, 2013

Simple Java Swing JSON formatter

Most of web developers that are using AJAX to retrieve data from the server will be using the JSON lightweight format (instead of XML) to encode the data. To help them with this, the web development consoles in all web browsers are capable to show a hierarchical view of received JSON data, and this is usually fine, but when the size of the data grows or its hierarchy becomes complicated, you need to copy the data out to study it. More specifically, I usually need to compare the differences in the responses of different calls to the server.

The problem here is that JSON data is generally encoded in a very long string without line breaks, so you must format the JSON first. Many online JSON formatters exist, but I just needed a simple non-remote tool to format large JSON strings, leaving each element in its own line and ordering the properties of the objects, so I wrote a little Java Swing program, JsonFormatter.java, helped by the json-simple Java toolkit. To use this program you need to download the json-simple JAR file in order to compile and run the program (see below), and do Ctrl+V/Ctrl+A/Ctrl+C to process the JSON text, along with a text editor capable of doing diff comparisons, like Vim. Use it!

To compile this program using the javac compiler, after putting the json-simple JAR file in the same directory (for example the 1.1.1 version), type: javac -cp json-simple-1.1.1.jar JsonFormatter.java

Then you could build a JAR file to run it easily, just typing: jar cfm json-formatter.jar MANIF-ADD.MF JsonFormatter*.class, where the MANIF-ADD.MF is a text file with the following two lines (ensuring that last line ends with a return):
Main-Class: JsonFormatter
Class-Path: json-simple-1.1.1.jar


After that, you only need the two JAR files, and to run it, if the double click doesn't work, you can type: java -jar json-formatter.jar

1 comment:

  1. You have worked to perfection on this article. Thanks for taking the time to post search valuable information. I Recommendation this. Online JSON Formatter

    ReplyDelete