【问题标题】:Gson - proper ways to check for node/element existanceGson - 检查节点/元素存在的正确方法
【发布时间】:2013-11-25 04:46:01
【问题描述】:

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

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

我的问题是,isJsonNull() 是检查元素是否存在的方法吗? Json 的文档让我有些困惑。

【问题讨论】:

  • 对于 java,互联网上有各种 Json 库。那么您使用的是哪个库。提供 JSON 库和文档的链接
  • @Thuy Trinh 看看我的答案。
  • @Veer 感谢您的指出。刚换成Gson。

标签: java android json parsing gson


【解决方案1】:

您可以使用 JsonObject.has() 来确定元素是否存在,http://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/index.html

【解决方案2】:

根据docsJsonNullJsonElement 但不是JsonObject(它本身就是JsonElement)。使用

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

如果不是 JsonNull 类型,将返回一个被强制转换为 JsonObjectJsonElement

null 引用不是 JsonNull 值。 (value == null)value.isJsonNull() 不同。它们非常不同。

文档描述了对JsonObject.get(String) 的调用返回"null if no such member exists." 他们没有说JsonNull 被返回。

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

【讨论】:

  • 谢谢。但是,关于上面的sn-p,你为什么不用source.getAsJsonObject()而不是这样的铸件呢?
猜你喜欢
  • 2019-02-26
  • 2015-02-14
  • 2022-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多