TL;DR: when my JSON array is converted to a list of Java objects, the null values in the JSON string is converted to 0 instead of staying as null.
I want to keep them as null in the Java object.
I have the following API response:
[
{
"ID": 1,
"MarginUpper": null
},
{
"ID": 2,
"MarginUpper": null
}
]
I also have the following POJO
package com.myapp.pojo;
import com.google.gson.annotations.SerializedName;
import lombok.Getter;
import lombok.Setter;
public class Margins {
@Getter
@Setter
@SerializedName("ID")
private int id;
@Getter
@Setter
@SerializedName("MarginUpper")
private int marginUpper;
// Constructor with all fields
public NaplanGain(int iId, int marginUpper) {
this.id = id;
this.marginUpper = marginUpper;
}
}
Using this code, I can convert the JSON string into a list of Java objects.
Type listType = new TypeToken<List<Margins>>() {}.getType();
List<Margins> list = new GsonBuilder().serializeNulls().create().fromJson(apiResponse, listType);
ID=1 will have a marginUpper=0 when I inspect the value when debugging
intcan not be null. Use ObjectsIntegerif you want to have null values