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

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

Mary-Kate Olsen
Release: 2024-11-27 10:25:10
Original
896 people have browsed it

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

Pretty-Print JSON Made Easy in Java

Pretty-printing JSON data makes it more readable and easier to understand. If you're using the json-simple library and haven't found a built-in pretty-printing feature, here's a commonly used solution:

Google's GSON library offers a convenient way to achieve this. Follow these steps:

  1. Create a Gson instance with pretty-printing enabled:

    1

    Gson gson = new GsonBuilder().setPrettyPrinting().create();

    Copy after login
  2. Create a JsonParser to parse the original JSON string:

    1

    2

    JsonParser jp = new JsonParser();

    JsonElement je = jp.parse(uglyJsonString);

    Copy after login
  3. Convert the parsed element to a pretty-printed JSON string:

    1

    String prettyJsonString = gson.toJson(je);

    Copy after login

For an even more up-to-date approach, use the static parse method from JsonParser instead:

1

2

JsonElement je = JsonParser.parseString​(uglyJsonString);

String prettyJsonString = gson.toJson(je);

Copy after login

Remember to include the following import statements:

1

import com.google.gson.*;

Copy after login

And add the following Gradle dependency:

1

implementation 'com.google.code.gson:gson:2.8.7'

Copy after login

By leveraging GSON, you can now easily convert raw JSON data into a human-readable format.

The above is the detailed content of How Can I Easily Pretty-Print JSON Data 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template