JSON 数组 Android 上的 NullPointer

NullPointer on JSON Array 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

我错过了什么?请帮忙...谢谢

试试这个:

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

您收到 JSONException,因为您的 JSONArray suggestionsresponse JSONObject 中。所以你需要做

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

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

因为你的List名称和List名称中的Object是一样的。 我建议你使用我的函数

 /** @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;
}