2015-05-21 54 views
0

我正在從服務器這樣的響應:空指針的JSON數組的Android

status: "ok", 
response: { 
suggestions: [ 
{ 
suggestion: "Cetri (10 mg)" 
}, 
{ 
suggestion: "Cetri-Plus (300 & 10)" 
}, 
{ 
suggestion: "Cetriax (1000 mg)" 
}, 
{ 
suggestion: "Cetricon (10 mg)" 
}, 
{ 
suggestion: "Cetrics (500 & 5 & 5)" 
} 
] 
} 

而且我這樣做是爲了獲取值:用一個空指針異常

String result = Utils.convertInputStreamToString(inputStream); 

      //Printing server response 
      System.out.println("server response is :" + result + "\n" + inputStream); 


      try { 
       JSONObject jsonResponse = new JSONObject(result); 
       js=jsonResponse.getJSONArray("suggestions"); 


      } catch (Exception e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 

      } 

但應用程序崩潰是

05-21 12:42:04.217: W/System.err(25961): org.json.JSONException: No value for suggestions 

我錯過了什麼?請幫助...感謝名單

+0

看起來像是缺少「{」 – inmyth

+1

是JSON的響應部分? 'jsonResponse.getJSONObject(「response」)。getJSONArray(「suggestions」);' – Anirudha

+0

首先在任何在線json解析器網站(https://www.jsoneditoronline.org/)檢查你的json字符串 – Pankaj

回答

3

試試這個:

JSONObject mainNode = new JSONObject(result); 
JSONObject jsonResponse = mainNode.getJSONObject("response"); 
js=jsonResponse.getJSONArray("suggestions"); 
1

你得到JSONException爲您JSONArray suggestions裏面response的JSONObject。所以你需要做

JSONObject jsonResponse = new JSONObject(result); 
jsonResponse = jsonResponse.getJSONObject ("response"); 

//and now you can use your code. 
js=jsonResponse.getJSONArray("suggestions"); 
0

因爲你列表的名字和列表中的對象是一樣的。 我建議你用我的功能

/** @param jObject The JSONObject to convert. 
* @return A list of two item lists: [String key, Object value]. 
* @throws JSONException if an element in jObject cannot be 
* converted properly. 
*/ 
@SuppressWarnings("unchecked") 
public static List<Object> getListFromJsonObject(JSONObject jObject) throws JSONException { 
     List<Object> returnList = new ArrayList<Object>(); 
     Iterator<String> keys = jObject.keys(); 
     List<String> keysList = new ArrayList<String>(); 
    while (keys.hasNext()) { 
    keysList.add(keys.next()); 
    } 
    Collections.sort(keysList); 

    for (String key : keysList) { 
    List<Object> nestedList = new ArrayList<Object>(); 
    nestedList.add(key); 
    nestedList.add(convertJsonItem(jObject.get(key))); 
    returnList.add(nestedList); 
    } 
    return returnList; 
}