Friday, January 29, 2016

Pretty Print JSON

Sure, online JSON Formatter is nice. Try this one here, for example: https://jsonformatter.curiousconcept.com/. It helps you understand your JSON. However, if your JSON is redicously large you need to make your own beautfier.

Json simple's JSONParser and Google's Gson can help you. First you need to find some jars.

Here is a simple Java program
import java.io.BufferedReader;
import java.io.FileReader;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
 

public class JSONPretty {

 public static void prettyPrint(String jsonString) {
  JsonParser parser = new JsonParser();
  JsonObject json = parser.parse(jsonString).getAsJsonObject();
 
  Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
  String prettyJson = prettyGson.toJson(json);
  System.out.println(prettyJson);

 }
 public static void main(String[] args) {

  if (args.length!=1) {
   System.out.println("USAGE: java JSONPretty [data.txt]\nwhere data.txt contains lines of JSON\n");
   return;
  }
  
  try {
 
   String fileName = args[0];
   BufferedReader readbuffer = new BufferedReader(new FileReader(fileName));
   String strRead;
   
   while ((strRead=readbuffer.readLine())!=null){
    prettyPrint(strRead);
   }
   readbuffer.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 

}

No comments: