-1

我是这个 android 编程的新手,我在解析 JSON 时遇到了问题。这是我想要解析Billers并查看到 ListView 的 JSON URL。我有一些我已经使用并成功提取我想要的值的代码。问题是我不能或者准确地说我在解析 JSON 数组时遇到了问题。这是我用于解析 JSON 数组的代码:

public class BillersJsonParser {
String mUrl;

public BillersJsonParser(String url){
    this.mUrl = url;
}

public BillersModel getCategories(){
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(mUrl);

    try {
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();

        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();

        String result = sb.toString();
        return parse(result);
    } catch (JSONException e) {
        return null;
    } catch (ClientProtocolException e) {
        return null;
    } catch (IOException e) {
        return null;
    }
}

private BillersModel parse(String result) throws JSONException{
    BillersModel billerList = new BillersModel();
    
    JSONObject jObject = new JSONObject(result);
    
    JSONArray bList = jObject.getJSONArray("billers");
    
    Log.e("BJSONParser 2nd Lvl: ", bList.toString());
    int length = bList.length();
    for (int i = 0; i < length; i++){
        billerList.setID(bList.getJSONObject(i).getString("bid"));
        billerList.setName(bList.getJSONObject(i).getString("name"));
        billerList.setStatus(bList.getJSONObject(i).getString("status"));
        billerList.setDateAdded(bList.getJSONObject(i).getString("date_added"));
    }
    return billerList;
}

}

每次运行此代码时,我都会收到 Null 异常错误,但我无法弄清楚。我怀疑当 eclipse 尝试运行这部分代码时错误开始JSONArray bList = jObject.getJSONArray("billers");。任何帮助将不胜感激。

4

1 回答 1

1

根据Billers的说法,您的 jObject IS JSONArray。而你在做什么 - 假设 jObject具有名为billersJSONObject的数组属性,例如

{"billers":[{"bid":"1","name":"biller1","logo":"","status":"1","date_added":"2013-03-20 23:03:55"},{"bid":"2","name":"biller2","logo":"","status":"1","date_added":"2013-03-20 23:03:55"},{"bid":"3","name":"biller3","logo":"","status":"1","date_added":"2013-03-20 23:04:06"},{"bid":"4","name":"biller4","logo":"","status":"1","date_added":"2013-03-20 23:04:06"}]}

是的,@njzk2 是对的,json 是 UTF-8。此外,您添加换行符的阅读"\n"看起来很奇怪。

于 2013-05-24T13:03:31.983 回答