Json Array在Android中解析时返回null

时间:2013-05-11 11:50:04

标签: android json parsing arrays

我知道这是一个非常常见的问题,我在SO中发现了相当多的帖子。 我的代码如下所示,我没有看到json数组返回null的原因。有人可以帮我查一下吗?我没留下任何石头! :(

JsonArray jsonArr = JSONfunctions.getJSONfromURL(url);
    try {
        if (jsonArr != null) {
            for (int i = 0; i < jsonArr.length(); i++) {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject jsonObj = jsonArr.getJSONObject(i);

                map.put(TAG_CODE, jsonObj.getString("Code"));
                map.put(TAG_DISPLAY_NAME, jsonObj.getString("UserName"));
                map.put(TAG_PROGRAM_NAME, jsonObj.getString("Password"));
                mylist.add(map);
            }
        }
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }                                                                                      






public class JSONfunctions {

public static JSONArray getJSONfromURL(String url) {
    InputStream is = null;
    String result = "";
    JSONArray jArray = null;

    // http post
    try {

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httppost = new HttpGet(url);
        // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();

                // Result is always returning me an array.(not null)

    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + result);
    }
    try {
        jArray = new JSONArray(result);

                // Goes into the catch block

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        Log.e("log_tag", "Error parsing result " + result);
    }
    return jArray;

}

}

1 个答案:

答案 0 :(得分:1)

服务器返回的内容({"FirstName": "\"firstname"", "LastName": "\"lastname\"", "Code": "\"id\""})是JSONObject而不是JSONArray,您应该更改

JSONArray jArray = null;

JSONOBject jArray = null;

jArray = new JSONArray(result);

jArray = new JSONOBject (result);