Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Gson: Convert json string to Pretty print json string

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
}

 

 

Previous                                                    Next                                                    Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Gson: Convert json string to Pretty print json string

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×