The docs say the JsonObject#get method returns null if no such member exists. That's not accurate; sometimes a JsonNull
object is returned instead of null
.
What is the idiom for checking whether a particular field exists in GSON? I wish to avoid this clunky style:
jsonElement = jsonObject.get("optional_field");
if (jsonElement != null && !jsonElement.isJsonNull()) {
s = jsonElement .getAsString();
}
Why did GSON use JsonNull
instead of null
?
There is an answer for what are the differences between null
and JsonNull
. In my question above, I'm looking for the reasons why.
JSONNull is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the value that JavaScript calls undefined. Author: JSON.org See Also: Serialized Form. Method Summary. boolean. equals(Object object)
Introduction. Gson is the main actor class of Google Gson library. It provides functionalities to convert Java objects to matching JSON constructs and vice versa. Gson is first constructed using GsonBuilder and then toJson(Object) or fromJson(String, Class) methods are used to read/write JSON constructs.
Gson, presumably, wanted to model the difference between the absence of a value and the presence of the JSON value null
in the JSON. For example, there's a difference between these two JSON snippets
{}
{"key":null}
your application might consider them the same, but the JSON format doesn't.
Calling
JsonObject jsonObject = new JsonObject(); // {}
jsonObject.get("key");
returns the Java value null
because no member exists with that name.
Calling
JsonObject jsonObject = new JsonObject();
jsonObject.add("key", JsonNull.INSTANCE /* or even null */); // {"key":null}
jsonObject.get("key");
returns an instance of type JsonNull
(the singleton referenced by JsonNull.INSTANCE
) because a member does exist with that name and its value is JSON null, represented by the JsonNull
value.
I know question is not asking for a solution, but I came here looking for one. So I will post it in case someone else needs it.
Below Kotlin extension code saves the trouble of checking for null
and isJsonNull
separately for each element
import com.google.gson.JsonElement
import com.google.gson.JsonObject
fun JsonObject.getNullable(key: String): JsonElement? {
val value: JsonElement = this.get(key) ?: return null
if (value.isJsonNull) {
return null
}
return value
}
and instead of calling like this
jsonObject.get("name")
you call like this
jsonObject.getNullable("name")
Works particularly great in nested structures. Your code eventually would look like this
val name = jsonObject.getNullable("owner")?.asJsonObject?.
getNullable("personDetails")?.asJsonObject?.
getNullable("name")
?: ""
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