GSON:.isJsonNull()问题

Jam*_*sev 7 null json gson

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

JsonElement value = e.getAsJsonObject().get(ENVIRONMENT);
Run Code Online (Sandbox Code Playgroud)

我的期望是,当你忘记这把钥匙时,我会得到null.事实证明我做到了.当我.get(ENVIRONMENT),返回的值是null.

当我测试它时,我实际得到一个" 非空 ".奇怪,综合考虑,GSON的Javadoc说" 提供的支票,如果这件代表空验证或不 "

if (value.isJsonNull()) {
    System.out.println("null");
} else {
    System.out.println("not null");
}
Run Code Online (Sandbox Code Playgroud)

请帮我更好地理解这一点.

Pro*_*uce 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;
  }
Run Code Online (Sandbox Code Playgroud)

这里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);
  }
Run Code Online (Sandbox Code Playgroud)

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

所以,我认为在"如果不存在这样的成员"这一条款中,"成员"的含义存在混淆.基于代码,我认为JavaDoc的作者指的是Java类中定义的成员.对于Gson API的临时用户 - 就像我自己一样 - 我假设"成员"引用了JSON中的对象元素.

现在,这个问题清楚了吗?

====

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

null引用不是一个JsonNull值. (value == null)是不一样的value.isJsonNull().他们是非常不同的.

文档描述了JsonObject.get(String)如果没有这样的成员,则返回"[n] ull".他们并没有说JsonNull退回.

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