I am trying to deserialize my own class with a null value. But my code doesn\'t work.
My json:
{\"Text\":null,\"Code\":0,\"Title\":\"This is Sparta!\
I had a similar problem (an exception thrown on null value) with the following POJO:
public class MyElement {
private String something;
private String somethingElse;
private JsonObject subEntry; // this doesn't allow deserialization of `null`!
}
and this code:
parsedJson = gson.fromJson(json, MyElement.class)
when subEntry returned by the backend was null.
I fixed it by changing the type of subEntry from JsonObject to JsonElement which is a parent class of both JsonObject and JsonNull, to allow deserialization of null values.
public class MyElement {
private String something;
private String somethingElse;
private JsonElement subEntry; // this allows deserialization of `null`
}
To later check for null at runtime, you'd do as follows:
if (parsedJson.subEntry instanceof JsonNull) {
...
} else {
...
}