Below snippet convert the json to Pretty json string.
String uglyJson = "{\"name\": \"Krishna\", \"age\": 31}";
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement jsonElement = JsonParser.parseString(uglyJson);
String prettyJsonString = gson.toJson(jsonElement);
Find the below working application.
PrettyJson.java
package com.sample.app.json;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class PrettyJson {
public static void main(String args[]) {
String uglyJson = "{\"name\": \"Krishna\", \"age\": 31}";
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonElement jsonElement = JsonParser.parseString(uglyJson);
String prettyJsonString = gson.toJson(jsonElement);
System.out.println(prettyJsonString);
}
}
Output
{
"name": "Krishna",
"age": 31
}
This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here