Tuesday, 14 December 2021

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

No comments:

Post a Comment