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

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

DDD
Release: 2024-11-28 07:43:13
Original
909 people have browsed it

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.*;
    Copy after login
  2. Specify the pretty printing setting:

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

    JsonElement je = JsonParser.parseString(uglyJsonString);
    Copy after login
  4. Convert the JSON element to a pretty-printed string:

    String prettyJsonString = gson.toJson(je);
    Copy after login

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);
Copy after login

Dependency

Integrate the following dependency in your Gradle configuration:

implementation 'com.google.code.gson:gson:2.8.7'
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template