Can't cast JsonNull to JsonObject

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.


According to the API reference, JsonNull derives from JsonElement and not JsonObject, so I don't see how that cast could ever be valid.

And have you considered using json-simple instead of gson? As a general rule I find it much more convenient to work with than other json frameworks, although of course it doesn't have a lot of the extra features that gson offers. But if all you're doing with gson is parsing json, it might be worth switching to the simpler library.


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

Which one will have better performance isJsonNull or using instanceOf operator ?

Tags:

Java

Json

Gson