Why JsonNull in GSON?

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") 
    ?: "" 

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.

Tags:

Java

Gson