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?
As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With