0

我想知道为什么我不能像这样读取 JSON 对象:

{
    "1":{"bulan":"Januari","tahun":"2012","tagihan":"205000","status":"Lunas"},
    "2":{"bulan":"Februari","tahun":"2012","tagihan":"180000","status":"Lunas"},
    "3":{"bulan":"Maret","tahun":"2012","tagihan":"120000","status":"Lunas"},
    "4":{"bulan":"April","tahun":"2012","tagihan":"230000","status":"Lunas"},
    "5":{"bulan":"Mei","tahun":"2012","tagihan":"160000","status":"Lunas"},
    "6":{"bulan":"Juni","tahun":"2012","tagihan":"150000","status":"Belum Lunas"},
    "panjang":6
}

用我的android代码是这样的:

    try {
        int length = jobj.getInt("panjang");

        for(int n = 0; n < length; n++){

            String m = Integer.toString(n)
            JSONObject row = jobj.getJSONObject(m);

            String bulan = row.getString("bulan");
            String tahun = row.getString("tahun");
            String tagihan = row.getString("tagihan");
            String status = row.getString("status");

            HashMap<String, String> map = new HashMap<String, String>();

            map.put("bulan", bulan);
            map.put("tahun", tahun);
            map.put("tagihan", tagihan);
            map.put("status", status);

            list.add(map);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

它总是什么都不返回,但是如果我将键 m 更改为特定键,例如 if

String m = "1";

我不能使用

JSONObject row = jobj.getJSONObject(n);

因为 getJSONObject() 只接受字符串,而不是 int。我的代码有问题吗?

4

1 回答 1

1

您的问题在于初始迭代器值。它无法搜索键“0”,因为您没有“0”。将其更改为:

for(int n = 1; n <= length; n++){

应该解决问题。

于 2012-06-25T03:13:06.683 回答