Gson – Serialize Null Values

The default behavior in Gson is that null fields are ignored. For example, if in Employee object, we do not specify the email (i.e. email is null) then the email will not be part of serialized JSON output.

Gson ignores null fields because this behavior allows a more compact JSON output format.

1. Default Behavior

To demonstrate the default behavior, suppose we have an Item record with two fields id and name.

public record Item(long id, String name) { }

If we serialize an Item with name field as null, in the output JSON, we will have only the id field.

String json = new Gson().toJson(new Item(1, null));

System.out.println(json);   //{"id":1}

2. GsonBuilder.serializeNulls()

To configure a Gson instance to output null values, we must use serializeNulls() of GsonBuilder object. After serialization, the null values are written as null. Note that null is a valid value in JSON.

Item item = new Item(1, null);

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

String itemJson = gson.toJson(item);

System.out.println(itemJson);   

Program output:

{"id":1,"name":null}

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.