Home >Java >javaTutorial >How Can I Pretty-Print JSON in Java Using GSON?

How Can I Pretty-Print JSON in Java Using GSON?

DDD
DDDOriginal
2024-11-28 07:43:13908browse

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:

  1. Import the GSON library into your project:

    import com.google.gson.*;
  2. Specify the pretty printing setting:

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
  3. Parse the JSON string to a JSON element:

    JsonElement je = JsonParser.parseString(uglyJsonString);
  4. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn