解析json数组

时间:2014-05-01 12:46:00

标签: android json

我正在尝试解析这个json:

    [{
    "codError": 0,
    "msg": "OK"
}, {
    "id": 1,
    "role": {
        "id": 4,
        "name": "Super",
        "description": "Roling.",
        "rights": [],
        "superuser": true,
        "active": true,
        "optimisticLock": 0
    },
    "now": null,
    "points": [],
    "firstName": null,
    "lastName": null,
    "loginName": "admin",
    "password": null,
    "connected": true,
    "active": true,
    "optimisticLock": null
},
["U4"]

]

我无法获取角色ID和loginName的值,我的代码在这里:

private static final String TAG_ROLE = "role";
private static final String TAG_ID = "id";

String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);

            Log.d("Response: ", "> " + jsonStr);

            if (jsonStr != null) {
                try {


                     JSONArray jsonarr =new  JSONArray(jsonStr);

                     JSONObject jobj=jsonarr.getJSONObject(1);
                     JSONObject role =jobj.getJSONObject(TAG_ROLE);
                     String role_id = role.getString(TAG_ID);



                } catch (JSONException e) {
                    e.printStackTrace();
                }

我调试我的app并且String role_id没有得到任何值,代码有什么问题?谢谢

1 个答案:

答案 0 :(得分:0)

JSONArray array;
array = new JSONArray(jsonStr);
JSONObject obj = array.getJSONObject(1);
JSONObject obj2 = obj.getJSONObject("role");
int id = obj2.getInt("id");
String name = obj2.getString("name");

如果您没有获得任何值,您可能需要检查响应是否与您期望的完全相同。另外,检查TAG_ROLE,TAG_ID的值。

编辑1:

String jsonStr = "[{\n    \"codError\": 0,\n    \"msg\": \"OK\"\n}, {\n    \"id\": 1,\n    \"role\": {\n        \"id\": 4,\n        \"name\": \"Super\",\n        \"description\": \"Roling.\",\n        \"rights\": [],\n        \"superuser\": true,\n        \"active\": true,\n        \"optimisticLock\": 0\n    },\n    \"now\": null,\n    \"points\": [],\n    \"firstName\": null,\n    \"lastName\": null,\n    \"loginName\": \"admin\",\n    \"password\": null,\n    \"connected\": true,\n    \"active\": true,\n    \"optimisticLock\": null\n},\n[\"U4\"]\n\n]";

try {
        JSONArray array;
        array = new JSONArray(jsonStr);
        JSONObject obj = array.getJSONObject(1);
        JSONObject obj2 = obj.getJSONObject("role");
        int id = obj2.getInt("id");
        String name = obj2.getString("name");
        System.out.println(id);
        System.out.println(name);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }