Core Java

Remove Whitespaces From a JSON String in Java

The JSON (JavaScript Object Notation) format is widely used for data interchange due to its simplicity and compatibility across different programming languages in modern-day software development. This guide will explore using the Jackson and Gson libraries to remove extra whitespaces from a JSON String in Java to minify it.

1. Introduction

JSON strings can sometimes contain unnecessary whitespaces, which can increase the payload size and potentially affect data transmission efficiency. To tackle this problem, developers often need to remove these whitespaces from JSON strings. In Java, this can be accomplished using Gson and Jackson, two popular libraries, which provide powerful tools for working with JSON data in Java. These two libraries offer efficient JSON parsing and serialization capabilities.

2. Reasons and Benefits of Removing Whitspaces from a JSON String

Removing whitespaces from a JSON string can have several reasons and benefits. It is important to note that removing whitespaces from a JSON String can make it less human-readable. Here are some benefits of removing whitespaces from a JSON string:

  • Reduced Data Size: JSON strings with whitespaces take up more space. In cases where network bandwidth or storage is a concern, minifying JSON by removing whitespaces can significantly reduce the data size and improve transmission speed.
  • Faster Transmission: Smaller JSON payloads due to whitespace removal can result in faster data transmission over networks with limited bandwidth.
  • Caching: Minified JSON is easier to cache, which can lead to performance improvements when using Content Delivery Networks or browser caching.
  • Improved Performance: When parsing JSON on the receiving end, removing whitespaces can lead to faster parsing times.
  • API Efficiency: APIs that deal with large amounts of JSON data may benefit from sending and receiving minified JSON to increase their efficiency and reduce response times.

3. Remove Whitepaces from a JSON String using Jackson

3.1 What is Jackson

Jackson is a widely used open-source Java library that provides different ways of working with JSON data in Java. Jackson is commonly used in Java applications to interact with web services, work with configuration files, and handle data interchange between systems.

3.2 Example of How to Remove Whitespaces from a JSON String using Jackson

The process of removing whitespaces from a JSON string using Jackson involves several steps. These steps range from importing the necessary packages to performing the whitespace removal using Jackson’s ObjectMapper class. First, we will create a Maven Java project named in an IDE of our choice, and add the Jackson library to our project by adding the following dependency to the dependencies section of the project’s pom.xml file

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

JSON data is commonly organized using colons ":" for differentiating keys and values, and commas "," to separate pairs of keys and values. Now, Let’s consider that we have the following JSON file named authors.json in the projects resources folder located at src/main/resources that we want to process.

    "name" :  "Chinua Achebe",
    "title"   :   "Things Fall Apart",
    "age" :       60   

We need to minify the above JSON data to optimize storage by removing the extra whitespace using Jackson. First, we need to create a Java class that matches the structure of the JSON data. Create a class AuthorObject that matches the structure of our JSON data. Jackson will automatically map the JSON properties to the corresponding fields in the AuthorObject class. We need to make sure the field names in the AuthorObject class match the property names in our JSON file.

Below is the code for the AuthorObject class:

public class AuthorObject {
    private String name;
    private String title;
    private int age;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String getTitle() {
        return title;

    public void setTitle(String title) {
        this.title = title;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public String toString() {
        return "AuthorObject{" + "name=" + name + ", title=" + title + ", age=" + age + '}';

Next, update the main method of our program to look like the example code below

public class WhitespaceRemovalJson {

    public static void main(String[] args) {

        //Create ObjectMapper Instance
        ObjectMapper objectMapper = new ObjectMapper();

        // Get the JSON file as an InputStream
        File jsonInput = new File("src/main/resources/authors.json");
        try {
            //Parse JSON String
            JsonNode jsonNode = objectMapper.readTree(jsonInput); 
            //Convert JsonNode to Compact JSON
            String jsonOutput = objectMapper.writeValueAsString(jsonNode);
            // Convert JSON string to a JSON object
            Object newNode = objectMapper.readTree(jsonOutput);
            // Write JSON object to a file
            objectMapper.writeValue(new File("src/main/resources/output.json"), newNode); 
            System.out.println("Original JSON:");

            System.out.println("Compact JSON:");

        } catch (IOException e) {


In the code above, We create an ObjectMapper Instance, which is used to handle JSON data in Jackson. Next, we read the JSON string that we want to process obtained from a file located in our resources folder. Next, we parse the JSON string using the readTree method of the ObjectMapper class. This will give us an JsonNode object representing the parsed JSON.

Next, convert the JsonNode back to a JSON string without whitespaces using the writeValueAsString method with the ObjectMapper. When we run the program, the resulting string will contain the JSON string without any unnecessary whitespace as shown in the screenshot output below:

Fig 1: Output after removing whitespaces from a JSON string
Fig 1: Output after removing whitespaces from a JSON string

4. Remove Whitespaces from a JSON String using Gson

Gson is a Java library developed by Google that simplifies the process of working with JSON data in Java applications. To remove whitespaces from a JSON object using Gson, Let’s create a Java Maven project and update the project’s pom.xml file to include Gson as a dependency by adding the following dependency to the <dependencies> section:

        <version>2.8.9</version> <!-- Use the latest version -->

Here’s an example code of how to remove whitespaces from a JSON String using GSON. Note that we also need to create a Java class that matches the structure of our JSON data.

public class RemoveWhitespaceGson {

    public static void main(String[] args) {
       String filePath = "src/main/resources/authors.json";

        try {
            // Read the JSON file content
            String jsonContent = new String(Files.readAllBytes(Paths.get(filePath)));

            // Remove all whitespaces from the JSON content
           JsonElement jsonWithoutWhitespace = JsonParser.parseString(jsonContent);

            // Create a Gson instance
            Gson gson = new GsonBuilder().create();            
            // Parse the modified JSON content
            AuthorObject jsonObject = gson.fromJson(jsonWithoutWhitespace, AuthorObject.class);

            // Convert the JSON object back to a JSON string without whitespace
            String compactJson = gson.toJson(jsonObject);
        } catch (IOException e) {

In this example, We start by using Java’s file reading mechanism to obtain the JSON string that we want to process from a file named authors.json in our application located at src/main/resources.

Next, we removed all whitespace characters from the JSON string using JsonElement jsonWithoutWhitespace = JsonParser.parseString(jsonContent);.

Next, we used Gson to deserialize the modified JSON string back into AuthorObject object with this code

 Gson gson = new GsonBuilder().create();            
 AuthorObject jsonObject = gson.fromJson(jsonWithoutWhitespace, AuthorObject.class);

Next, we serialize the parsed AuthorObject object back into a JSON string without whitespaces and print it out to the screen using the following code

String compactJson = gson.toJson(jsonObject);

5. Conclusion

In this article, we discussed several benefits of removing whitespaces from JSON data. We explored two popular Java libraries, Jackson and Gson, and, also showed some examples and methods to achieve whitespace removal from JSON, using these third-party libraries.

In conclusion, Gson and Jackson provide libraries that equip you to effectively remove whitespaces from a JSON string to minify it, which significantly reduces the data’s size, leading to improved data transfer speed and reduced storage requirements.

6. Download the Source Code

This was an example of how to remove whitespaces from a JSON String to minify it in Java.

You can download the full source code of this example here: Remove Whitespaces From a JSON String in Java

Omozegie Aziegbe

Omos holds a Master degree in Information Engineering with Network Management from the Robert Gordon University, Aberdeen. Omos is currently a freelance web/application developer who is currently focused on developing Java enterprise applications with the Jakarta EE framework.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button