Try it yourself with our free Json Formatter tool — runs entirely in your browser, no signup needed.

How to Format JSON in Java

How to Format JSON in Java

Formatting JSON data in Java is an essential task when working with JSON data, as it makes the data more human-readable and easier to debug. In this article, we will explore how to format JSON in Java using the popular Jackson library.

Quick Example

Here is a minimal example of how to format JSON in Java using Jackson:

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonFormatter {
    public static String formatJson(String jsonString) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(jsonString);
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
    }

    public static void main(String[] args) throws Exception {
        String jsonString = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
        String formattedJson = formatJson(jsonString);
        System.out.println(formattedJson);
    }
}

This code uses the ObjectMapper class to parse the JSON string into a JsonNode object, and then uses the writerWithDefaultPrettyPrinter() method to format the JSON data with indentation and line breaks.

Step-by-Step Breakdown

Let's break down the code line by line:

  • import com.fasterxml.jackson.databind.JsonNode;: We import the JsonNode class, which represents a node in the JSON data tree.
  • import com.fasterxml.jackson.databind.ObjectMapper;: We import the ObjectMapper class, which is used to parse and generate JSON data.
  • import com.fasterxml.jackson.databind.SerializationFeature;: We import the SerializationFeature class, which is used to configure the JSON serialization process.
  • public static String formatJson(String jsonString) throws Exception {: We define a method formatJson that takes a JSON string as input and returns the formatted JSON string.
  • ObjectMapper mapper = new ObjectMapper();: We create an instance of the ObjectMapper class.
  • JsonNode jsonNode = mapper.readTree(jsonString);: We use the readTree method to parse the JSON string into a JsonNode object.
  • return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);: We use the writerWithDefaultPrettyPrinter method to format the JSON data with indentation and line breaks, and then use the writeValueAsString method to convert the formatted JSON data to a string.

Handling Edge Cases

Here are some common edge cases to consider:

Empty/Null Input

If the input JSON string is empty or null, the readTree method will throw a JsonParseException. We can handle this by adding a null check:

if (jsonString == null || jsonString.isEmpty()) {
    return "";
}

Invalid Input

If the input JSON string is invalid, the readTree method will throw a JsonParseException. We can handle this by catching the exception and returning an error message:

try {
    JsonNode jsonNode = mapper.readTree(jsonString);
    // ...
} catch (JsonParseException e) {
    return "Invalid JSON input";
}

Large Input

If the input JSON string is very large, the readTree method may throw an OutOfMemoryError. We can handle this by using a streaming API such as the JsonParser class:

JsonParser parser = mapper.createParser(jsonString);
// ...

Unicode/Special Characters

If the input JSON string contains Unicode or special characters, the readTree method may throw a JsonParseException. We can handle this by configuring the ObjectMapper instance to use a specific character encoding:

mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

Common Mistakes

Here are some common mistakes to avoid:

  • Not handling null or empty input:
// Wrong code
public static String formatJson(String jsonString) {
    JsonNode jsonNode = mapper.readTree(jsonString);
    // ...
}

// Corrected code
public static String formatJson(String jsonString) {
    if (jsonString == null || jsonString.isEmpty()) {
        return "";
    }
    JsonNode jsonNode = mapper.readTree(jsonString);
    // ...
}
  • Not handling invalid input:
// Wrong code
public static String formatJson(String jsonString) {
    JsonNode jsonNode = mapper.readTree(jsonString);
    // ...
}

// Corrected code
public static String formatJson(String jsonString) {
    try {
        JsonNode jsonNode = mapper.readTree(jsonString);
        // ...
    } catch (JsonParseException e) {
        return "Invalid JSON input";
    }
}
  • Not handling large input:
// Wrong code
public static String formatJson(String jsonString) {
    JsonNode jsonNode = mapper.readTree(jsonString);
    // ...
}

// Corrected code
public static String formatJson(String jsonString) {
    JsonParser parser = mapper.createParser(jsonString);
    // ...
}

Performance Tips

Here are some performance tips to keep in mind:

  • Use the ObjectMapper instance to parse and generate JSON data, as it is more efficient than using the JsonParser class.
  • Use the writerWithDefaultPrettyPrinter method to format the JSON data with indentation and line breaks, as it is more efficient than using a custom pretty printer.
  • Use the SerializationFeature class to configure the JSON serialization process, as it can improve performance by reducing the amount of data written to the output stream.

FAQ

Q: What is the minimum Java version required to use the Jackson library?

A: The minimum Java version required to use the Jackson library is Java 6.

Q: How do I install the Jackson library in my Maven project?

A: You can install the Jackson library in your Maven project by adding the following dependency to your pom.xml file:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.12.3</version>
</dependency>

Q: How do I configure the ObjectMapper instance to use a specific character encoding?

A: You can configure the ObjectMapper instance to use a specific character encoding by using the configure method:

mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);

Q: How do I handle null or empty input when using the readTree method?

A: You can handle null or empty input when using the readTree method by adding a null check:

if (jsonString == null || jsonString.isEmpty()) {
    return "";
}

Q: How do I handle invalid input when using the readTree method?

A: You can handle invalid input when using the readTree method by catching the JsonParseException exception:

try {
    JsonNode jsonNode = mapper.readTree(jsonString);
    // ...
} catch (JsonParseException e) {
    return "Invalid JSON input";
}

AI agent tools available. The CodeTidy MCP Server gives Claude, Cursor, and other AI agents access to 60+ developer tools. One command: npx @codetidy/mcp