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

Viewed 1129

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?

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.

Related