Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson.fromJson not failing if some fields are not given even though marked as @NonNull

Tags:

java

gson

lombok

I have a POJO defined as follows:

@Value
public class Abc {

    @NonNull
    private final String id;

    @NonNull
    private final Integer id2;

    @NonNull
    private final List<String> data;

    @NonNull
    private final String otherData;
}

When I am doing,

GSON.fromJson(str, Abc.class);

with str as:

{
"id": "dsada",
"id2": 12,
"data": ["dsadsa"]
}

In this, there is no otherData field. Even then, GSON.fromJson is not failing. Why is it so? Then, is there any significance of marking the field as @NonNull?

like image 798
hatellla Avatar asked Jun 30 '19 20:06

hatellla


People also ask

Does Gson ignore extra fields?

As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.

How do you handle null in Gson?

We can force Gson to serialize null values via the GsonBuilder class. We need to call the serializeNulls() method on the GsonBuilder instance before creating the Gson object. Once serializeNulls() has been called the Gson instance created by the GsonBuilder can include null fields in the serialized JSON.

Does Gson require a default constructor?

Gson requires the class to have a default no-args constructor. If the no-args constructor is not provided, we can register an InstanceCreator with Gson, allowing us to deserialize instances of classes.

What is use of Gson in Java?

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.


1 Answers

Altgough with lombok @Value you get a allArgs constructor, Gson will not use it. Note that lombok will generate the allArg constructor for you so there will be no noArg constructor - but that will not be a problem for Gson (beggining from Gson 2.3.1 - check this SO question).

@NonNull annotation will make lombok generate null checks inside the constructor but this constructor will not be invoked. That is why Gson will read your Json without any problem.

like image 93
Michał Krzywański Avatar answered Sep 29 '22 02:09

Michał Krzywański