Remove null values from JSON in Java

In this tutorial we have given example for removing null values from JSON in Java.

Remove null values from JSON in Java

Example of Removing null values from JSON in Java

These days JSON is the most preferred format for data transfer and storage in the software industry. JSON is being used in almost all the technologies for sending and receiving the data between applications developed in different technologies.

In this tutorial we will provide you example in Java which removes the null value element while generating the JSON text. Sometime it is necessary to remove the elements having null values. For example if you are saving the data into NoSQL database you would like to remove the null value elements. So, in this case this simple Java program will do the magic for you and remove all the elements having null values.

We have used the google gson library in the example program. You should add following maven dependency to include the google gson library in your projects:


	<dependency>
	    <groupId>com.google.code.gson</groupId>
	    <artifactId>gson</artifactId>
	    <version>2.8.5</version>
	</dependency> 

Here is the screen of the program running in Eclipse IDE:

Remove null values from JSON in Java

Here is the source code of the program that removes the nodes with null values from generated JSON text:


package net.roseindia;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;

public class RemovingNullValuesJSON {

public static void main(String[] args) {
	String json = "{\"name\": \"Rajesh Roy\", \"country\": \"India\", \"address\":null}";
	JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
	System.out.println("Original JOSN: \n" + json);
	String s = jsonObject.toString();
	Gson gson = new GsonBuilder().create();
	System.out.println("jsonObject.toString() Output: \n" + s);
	s = gson.toJson(jsonObject);
	System.out.println("gson.toJson - output which removes null: \n" + s);

}
}

In our example we have one node "address"  with null value and program removes it from generated json. If you run the program you will get following output:


Original JOSN: 
{"name":"Rajesh Roy","country":"India","address":null}
jsonObject.toString() Output: 
{"name":"Rajesh Roy","country":"India","address":null}
gson.toJson - output which removes null: 
{"name":"Rajesh Roy","country":"India"}

In the program we have created the object of Gson as shown below:

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

Then called gson.toJson(jsonObject) method which removes the null valued nodes from the generated JSON text. Here is the code example:

s = gson.toJson(jsonObject);

In this I have provided you the example code for generating the JSON text from the Java program which removes null values nodes.

Here are more tutorials of JSON: