8

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?

Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63
hatellla
  • 4,796
  • 8
  • 49
  • 101
  • Maybe this answers your question: https://stackoverflow.com/questions/21626690/gson-optional-and-required-fields – ich5003 Jun 30 '19 at 20:27

1 Answers1

3

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.

Michał Krzywański
  • 15,659
  • 4
  • 36
  • 63