JSON阵列Android上的NullPointer

时间:2015-05-21 07:13:40

标签: android arrays android-json

我从服务器获得此响应:

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

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

3 个答案:

答案 0 :(得分:3)

试试这个:

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

答案 1 :(得分: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");

答案 2 :(得分:0)

因为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;
}