gosua gosua - 4 months ago 9
JSON Question

Can't cast JsonNull to JsonObject

I want to copy one primitve property from one JsonObject to another

JsonObject propertyToBeCopied = source.getAsJsonObject(propertyName);


but I always run into this exception:

com.google.gson.JsonNull cannot be cast to com.google.gson.JsonObject


According to the documentation it should be possible to do the cast, or am I wrong?

Pao Pao
Answer

According to the docsJsonNull is a JsonElement but not a JsonObject (which is itself a JsonElement). Using

JsonElement element = source.get(propertyName);
if (!(element instanceof JsonNull)) {
    JsonObject propertyToBeCopied = (JsonObject) element;
}

would return a JsonElement that is casted to JsonObject if it is not of the type JsonNull.

Comments