Home >Java >javaTutorial >How Can I Pretty-Print JSON in Java Using GSON?
Pretty-Print JSON in Java Using GSON
Manipulating JSON data requires tools that facilitate its readability and comprehension. For those utilizing the json-simple library and seeking a means to prettify their JSON data, GSON, developed by Google, presents a reliable solution.
Pretty-Printing JSON with GSON
To achieve pretty-printed JSON using GSON, follow these steps:
Import the GSON library into your project:
import com.google.gson.*;
Specify the pretty printing setting:
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Parse the JSON string to a JSON element:
JsonElement je = JsonParser.parseString(uglyJsonString);
Convert the JSON element to a pretty-printed string:
String prettyJsonString = gson.toJson(je);
Example Code
The following code snippet demonstrates the usage of GSON for pretty-printing JSON:
Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonElement je = JsonParser.parseString(uglyJsonString); String prettyJsonString = gson.toJson(je); System.out.println(prettyJsonString);
Dependency
Integrate the following dependency in your Gradle configuration:
implementation 'com.google.code.gson:gson:2.8.7'
Using GSON provides an elegant solution for prettifying JSON data in Java, enhancing its readability and usability for debugging or presentation purposes.
The above is the detailed content of How Can I Pretty-Print JSON in Java Using GSON?. For more information, please follow other related articles on the PHP Chinese website!