別管我下面的第一個答案。我很快就讀到了這個問題。
看起來這是一個簡單的文件撒謊案例 - 至少是被誤解了。幸運的是,代碼並不那麼容易,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);
}
呼叫添加到members
在Java類中定義的每個部件由 - 它不是基於什麼在JSON中。 (對於那些感興趣的,在ReflectingFieldNavigator
的visitFieldsReflectively
方法填充成員)。
所以,我想混淆是圍繞「成員」的意思在「如果沒有這樣的成員存在」的條款。根據代碼,我收集到JavaDoc的作者是指在Java類中定義的成員。對於Gson API的偶然用戶 - 就像我自己 - 我認爲「成員」指的是JSON中的一個對象元素。
現在,這個問題清楚了嗎?
====
首先基於問題的快速閱讀答案(保留有用的鏈接):
一個null
引用不是JsonNull
值。 (value == null)
與value.isJsonNull()
不一樣。他們是非常不同的。
文檔描述如果沒有這樣的成員存在,那麼對JsonObject.get(String)
的調用返回「[n] ull」。他們不會說JsonNull
被返回。
對JsonElement.isJsonNull()
的調用不檢查JsonElement
參考是否爲null
參考。事實上,如果它是一個null
參考,調用它的方法會拋出一個NullPointerException
。它正在檢查它是否是JsonNull
實例。
您是否嘗試過打印由e.getAsJsonObject()返回的實現類。得到(環境); ? – OverLex 2011-06-06 14:07:12
是的。它實際上是「空」 – JAM 2011-06-06 16:39:50
它是空引用還是JsonNull引用?我假設它是一個JsonNull引用。 – 2011-06-06 20:25:25