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

How to Minify JSON in Java

How to Minify JSON in Java

Minifying JSON is the process of removing unnecessary characters from a JSON string, such as whitespace, line breaks, and comments, to reduce its size and improve transmission efficiency. This is particularly important when working with large JSON data sets or when transmitting JSON data over a network. In this guide, we will explore how to minify JSON in Java.

Quick Example

Here is a minimal example of how to minify JSON in Java using the Jackson library:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonMinifier {
    public static String minifyJson(String json) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(json);
        return mapper.writeValueAsString(jsonNode);
    }

    public static void main(String[] args) throws JsonProcessingException {
        String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
        String minifiedJson = minifyJson(json);
        System.out.println(minifiedJson);
    }
}

To use this code, you need to add the Jackson library to your project. If you're using Maven, add 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>

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

dependencies {
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.12.3'
}

Step-by-Step Breakdown

Let's walk through the code line by line:

  • ObjectMapper mapper = new ObjectMapper();: Creates a new instance of the ObjectMapper class, which is the main class used for data-binding in Jackson.
  • JsonNode jsonNode = mapper.readTree(json);: Reads the JSON string into a JsonNode object, which is a tree-like representation of the JSON data.
  • return mapper.writeValueAsString(jsonNode);: Writes the JsonNode object back into a JSON string, but this time without unnecessary characters.

Handling Edge Cases

Here are a few common edge cases to consider:

Empty/Null Input

If the input JSON string is empty or null, the readTree() method will throw a JsonProcessingException. You can handle this by adding a null check and returning an empty string or throwing a custom exception:

public static String minifyJson(String json) throws JsonProcessingException {
    if (json == null || json.isEmpty()) {
        return "";
    }
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree(json);
    return mapper.writeValueAsString(jsonNode);
}

Invalid Input

If the input JSON string is invalid, the readTree() method will throw a JsonProcessingException. You can handle this by catching the exception and returning an error message or throwing a custom exception:

public static String minifyJson(String json) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(json);
        return mapper.writeValueAsString(jsonNode);
    } catch (JsonProcessingException e) {
        return "Invalid JSON input";
    }
}

Large Input

If the input JSON string is very large, the readTree() method may throw an OutOfMemoryError. You can handle this by using a streaming API, such as the JsonParser class, to parse the JSON data in chunks:

public static String minifyJson(String json) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    JsonParser parser = mapper.createParser(json);
    JsonNode jsonNode = mapper.readTree(parser);
    return mapper.writeValueAsString(jsonNode);
}

Unicode/Special Characters

If the input JSON string contains Unicode or special characters, the writeValueAsString() method may not escape them correctly. You can handle this by using the JsonGenerator class to write the JSON data with the correct escaping:

public static String minifyJson(String json) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree(json);
    JsonGenerator generator = mapper.createGenerator(new StringWriter());
    generator.writeTree(jsonNode);
    return generator.toString();
}

Common Mistakes

Here are a few common mistakes developers make when minifying JSON in Java:

Mistake 1: Not Handling Null Input

public static String minifyJson(String json) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree(json); // throws NullPointerException if json is null
    return mapper.writeValueAsString(jsonNode);
}

Corrected code:

public static String minifyJson(String json) throws JsonProcessingException {
    if (json == null) {
        return "";
    }
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree(json);
    return mapper.writeValueAsString(jsonNode);
}

Mistake 2: Not Handling Invalid Input

public static String minifyJson(String json) {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree(json); // throws JsonProcessingException if json is invalid
    return mapper.writeValueAsString(jsonNode);
}

Corrected code:

public static String minifyJson(String json) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode jsonNode = mapper.readTree(json);
        return mapper.writeValueAsString(jsonNode);
    } catch (JsonProcessingException e) {
        return "Invalid JSON input";
    }
}

Mistake 3: Not Using a Streaming API for Large Input

public static String minifyJson(String json) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree(json); // throws OutOfMemoryError if json is large
    return mapper.writeValueAsString(jsonNode);
}

Corrected code:

public static String minifyJson(String json) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    JsonParser parser = mapper.createParser(json);
    JsonNode jsonNode = mapper.readTree(parser);
    return mapper.writeValueAsString(jsonNode);
}

Performance Tips

Here are a few performance tips for minifying JSON in Java:

  • Use a streaming API, such as the JsonParser class, to parse large JSON data sets.
  • Use a BufferedWriter to write the minified JSON data to a file or output stream.
  • Use the JsonGenerator class to write the JSON data with the correct escaping.

FAQ

Q: What is the difference between minifying and compressing JSON data?

A: Minifying JSON data removes unnecessary characters, while compressing JSON data reduces the size of the data using algorithms such as GZIP or ZIP.

Q: How do I handle Unicode characters in JSON data?

A: Use the JsonGenerator class to write the JSON data with the correct escaping.

Q: What is the maximum size of JSON data that can be minified?

A: There is no maximum size limit, but very large JSON data sets may cause an OutOfMemoryError. Use a streaming API to parse large JSON data sets.

Q: Can I minify JSON data in a multi-threaded environment?

A: Yes, but make sure to synchronize access to the ObjectMapper instance.

Q: How do I handle null or empty JSON input?

A: Return an empty string or throw a custom exception.

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