GSON:.isJsonNull()问题

问题描述 投票:7回答:1

我正在读取JSON文件(使用Google的GSON)。我的一项测试在缺少给定密钥的事件文件中检查程序的行为。

JsonElement value = e.getAsJsonObject().get(ENVIRONMENT);

我的期望是,当.get(ing)此键时,我会得到null。原来我愿意。当我.get(ENVIRONMENT)时,返回的值为null

当我测试它时,我实际上得到一个“ not null”。很奇怪,考虑到,GSON的javadoc说“ 提供检查以验证此元素是否表示空value或不

if (value.isJsonNull()) {
    System.out.println("null");
} else {
    System.out.println("not null");
}

请帮助我更好地理解这一点。

json null gson
1个回答
15
投票

不要介意我的第一个答案。我读得太快了。

看来这是文件说谎的简单情况-或至少被误解了。幸运的是,代码并非易事,Gson是一个开源项目。

这里是JsonObject.get(String)

  /**
   * Returns the member with the specified name.
   *
   * @param memberName name of the member that is being requested.
   * @return the member matching the name. Null if no such member exists.
   */
  public JsonElement get(String memberName) {
    if (members.containsKey(memberName)) {
      JsonElement member = members.get(memberName);
      return member == null ? JsonNull.INSTANCE : member;
    }
    return null;
  }

这里是members的填充位置:

  /**
   * Adds a member, which is a name-value pair, to self. The name must be a String, but the value
   * can be an arbitrary JsonElement, thereby allowing you to build a full tree of JsonElements
   * rooted at this node.
   *
   * @param property name of the member.
   * @param value the member object.
   */
  public void add(String property, JsonElement value) {
    if (value == null) {
      value = JsonNull.INSTANCE;
    }
    members.put($Gson$Preconditions.checkNotNull(property), value);
  }

对Java类中定义的每个成员进行添加到members的调用-它不基于JSON中的内容。 (对于那些感兴趣的人,visitFieldsReflectively中的ReflectingFieldNavigator方法将填充成员。)

因此,我想混淆“如果不存在这样的成员”子句中“成员”的含义。根据代码,我认为JavaDoc的作者引用的是Java类中定义的成员。对于像我一样的Gson API临时用户,我认为“成员”是指JSON中的对象元素。

现在,这个问题清楚吗?

====

基于快速阅读的问题的第一个答案(保留有用的链接):

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

文档描述,如果没有这样的成员,对JsonObject.get(String)的调用将返回“ [n] ull”。他们没有说返回JsonObject.get(String)

JsonNull的调用未检查JsonElement.isJsonNull()参考是否为JsonElement参考。实际上,如果它是null引用,则在其上调用方法将抛出null。它正在检查它是否为NullPointerException实例。

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