Friday, 17 February 2017

How to convert simple JSON String to Pretty Print in Java?

Today we'll see how to convert a simple JSON String to Pretty Print using Java and GSON. Sometimes we may be required to indent a simple JSON String for displaying in proper format.

We will be converting the simple JSON String using GSON (GSON is a Java API, developed by Google, used to convert between Java objects and JSON objects). We will be using gson-2.2.2.jar in our example for GSON API.

Now let us see the example -

package com.anjan.gson;

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

public class JSONIndentDemo {

public static String indentJSON(String jsonString) {

JsonParser parser = new JsonParser();
JsonObject json = parser.parse(jsonString).getAsJsonObject();

Gson gson new GsonBuilder().setPrettyPrinting().create();
String prettyJson = gson.toJson(json);

return prettyJson;

}

public static void main(String args[]) {

String str = "{\"attributes\":[{\"nm\":\"ACCOUNT\",\"lv\":[{\"vt\":\"java.util.Map\",\"cn\":1}],\"vt\":\"java.util.Map\",\"status\":\"SUCCESS\",\"lmd\":13585},{\"nm\":\"PROFILE\",\"lv\":[{\"vt\":\"java.util.Map\",\"cn\":2}],\"vt\":\"java.util.Map\",\"status\":\"SUCCESS\",\"lmd\":41962}]}";
System.out.println("Simple String :\n"+str);
String output = indentJSON(str);
System.out.println("\n\nIndented String :\n"+output);

}

}


Output -

Simple String :
{"attributes":[{"nm":"ACCOUNT","lv":[{"vt":"java.util.Map","cn":1}],"vt":"java.util.Map","status":"SUCCESS","lmd":13585},{"nm":"PROFILE","lv":[{"vt":"java.util.Map","cn":2}],"vt":"java.util.Map","status":"SUCCESS","lmd":41962}]}


Indented String :
{
  "attributes": [
    {
      "nm": "ACCOUNT",
      "lv": [
        {
          "vt": "java.util.Map",
          "cn": 1
        }
      ],
      "vt": "java.util.Map",
      "status": "SUCCESS",
      "lmd": 13585
    },
    {
      "nm": "PROFILE",
      "lv": [
        {
          "vt": "java.util.Map",
          "cn": 2
        }
      ],
      "vt": "java.util.Map",
      "status": "SUCCESS",
      "lmd": 41962
    }
  ]
}

No comments:

Post a Comment