2011-04-08 57 views
2

我正在使用JSON-lib來解析對象並從中讀取字符串。這適用於有效的字符串,但也可以爲null。例如:是否有可能使用JSONLib從getString中獲得空值

JSONObject jsonObject = JSONObject.fromObject("{\"foo\":null}"); 
String str = jsonObject.getString("foo"); 

在這種情況下,我希望strnull但它是不是"null"。調用任何其他方法似乎會引發錯誤。無論如何有JSONLib解析一個字符串,如果該值是一個字符串,但如果值爲空返回null?

+0

這是真正的源代碼嗎? fromObject調用的「參數」看起來不像有效的Java。 – 2011-04-08 12:39:21

+0

很對,我會更新 – slashnick 2011-04-08 12:55:00

+1

JSONLib是廢話。改爲使用[GSON](http://code.google.com/p/google-gson/)或[Jackson](http://jackson.codehaus.org/)。 – 2011-04-08 12:59:36

回答

3

JSONObject.java:

/** 
* Get the string associated with a key. 
* 
* @param key A key string. 
* @return A string which is the value. 
* @throws JSONException if the key is not found. 
*/ 
public String getString(String key) { 
    verifyIsNull(); 
    Object o = get(key); 
    if(o != null){ 
     return o.toString(); 
    } 
    throw new JSONException("JSONObject[" + JSONUtils.quote(key) + "] not found."); 
} 

你可以看到的getString()永遠不會返回null。它可以返回「null」,如果o.toString()這樣做,但這將是字符串非空值

1

我找不到一個很好的方式來做到這一點,所以我切換到Jackson來代替。這讓我做:

JsonNode json = (new ObjectMapper()).readValue("{\"foo\":null}", JsonNode.class); 
json.get("stopType").getTextValue(); 

將返回null在這個例子中,符合市場預期。

相關問題