How to pretty-print existing JSON data with Java?

How to pretty-print existing JSON data with Java?

To pretty-print existing JSON data in Java, you can use a JSON library to parse the JSON string and then serialize it back to a formatted JSON string with proper indentation. One commonly used library for this purpose is the Jackson library. Here's how you can do it:

  1. Add Jackson Dependency:

    Include the Jackson library in your project. You can add the following Maven dependency to your pom.xml:

    <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.5</version> <!-- Use the latest version --> </dependency> 

    If you're using Gradle, add the equivalent dependency to your build.gradle file.

  2. Pretty-Print JSON:

    Now, you can use Jackson to pretty-print your existing JSON data. Here's a simple example:

    import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class JsonPrettyPrinter { public static void main(String[] args) throws Exception { // Your existing JSON data as a string String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}"; // Create an ObjectMapper ObjectMapper objectMapper = new ObjectMapper(); // Parse the JSON string into a JsonNode JsonNode jsonNode = objectMapper.readTree(json); // Convert the JsonNode back to a pretty-printed JSON string String prettyJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode); // Print the pretty-printed JSON System.out.println(prettyJson); } } 

    In this example:

    • ObjectMapper is used to parse the existing JSON string into a JsonNode.
    • objectMapper.writerWithDefaultPrettyPrinter() returns a writer with a default pretty-printing configuration.
    • writeValueAsString(jsonNode) serializes the JsonNode back into a formatted JSON string.

    You can replace the json variable with your existing JSON data as a string.

  3. Output:

    Running the above code will produce a pretty-printed JSON string that you can use or display as needed:

    { "name" : "John", "age" : 30, "city" : "New York" } 

With the Jackson library, you can easily pretty-print existing JSON data in Java. Make sure to handle exceptions that may occur during JSON parsing and serialization, such as JsonProcessingException.


More Tags

wave jspdf-autotable writer vgg-net express coalesce highlight errno flask-sqlalchemy rlang

More Java Questions

More Cat Calculators

More Mixtures and solutions Calculators

More Entertainment Anecdotes Calculators

More Pregnancy Calculators