Gson - 检查节点/元素存在的正确方法

问题描述 投票:0回答:2

当我有一个

JsonObject
时,为了从中检索指定的元素成员,会有几个方法,例如,
get()
和其他
getAsXXX()

JsonPrimitive childNode1 = parent.getAsJsonPrimitive("key1);
JsonArray childNode2 = parent.getAsJsonArray("key2);
JsonElement childNode3 = parent.get("key3);

我的问题是,

isJsonNull()
是检查元素是否存在的方法吗?我对 Json 的文档有点困惑。

java android json parsing gson
2个回答
7
投票

您可以使用 JsonObject.has() 来确定元素是否存在。

参见代码定义


6
投票

根据docs

JsonNull
是一个
JsonElement
,但不是
JsonObject
(它本身就是一个
JsonElement
)。使用

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

将返回一个

JsonElement
,如果它不是
JsonObject
类型,则将其转换为
JsonNull

null
参考不是
JsonNull
值。
(value == null)
value.isJsonNull()
不同。他们非常不同。

文档描述了对

JsonObject.get(String)
的调用返回
"null if no such member exists."
他们没有说返回
JsonNull

JsonElement.isJsonNull()
的调用不会检查
JsonElement
引用是否是
null
引用。事实上,如果它是一个
null
引用,调用它的方法会抛出一个
NullPointerException
。它正在检查它是否是一个
JsonNull
实例。

© www.soinside.com 2019 - 2024. All rights reserved.