问题
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?
回答1:
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.
回答2:
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.
回答3:
JsonElement element = source.get(propertyName);
if (!(element.isJsonNull())) {
JsonObject propertyToBeCopied = (JsonObject) element;
}
Which one will have better performance isJsonNull or using instanceOf operator ?
回答4:
If output do not have a Response array then there is a chance why this error is thrown.
JsonObject playListObject = (JsonObject) parser.parse(output);
JsonArray playListInformationArray = playListObject.getAsJsonArray("Response");
来源:https://stackoverflow.com/questions/12379405/cant-cast-jsonnull-to-jsonobject