如何在android中解析这个嵌套的JSON数组和JSON对象View_ID

时间:2017-08-15 01:24:53

标签: java android json

  

如何获取"View_ID":"v1"View数组   我创建的内容并未产生正确的响应。我做错了什么?

以下是我得到的回复:

{"success":true,"total":2,"View_ID":"v1","View":[{"id":"1","Button_ID":"acc123_b1","Publish_Topic":"\/ziniks\/acc123\/sw1","Subscribe_Topic":"\/ziniks\/acc123\/sw1_status"},{"id":"2","Button_ID":"acc123_b2","Publish_Topic":"\/ziniks\/acc123\/sw2","Subscribe_Topic":"\/ziniks\/acc123\/sw2_status"}]}

我为获得回应而创建的内容:

JSONObject mainObj = new JSONObject(response);
if(mainObj != null){
    JSONArray list = mainObj.getJSONArray("View");
    if(list != null){
        for(int j = 0; j < list.length();j++){
            JSONObject innerElem = list.getJSONObject(j);
            if(innerElem != null){
                String button_id = innerElem.getString("Button_ID");
                Toast.makeText(QRCode.this, button_id, Toast.LENGTH_SHORT).show();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

    Try bellow.


JSONObject mainObj = new JSONObject(response); if(mainObj != null){
    String viewid = mainObj.getString("View_ID");  // here is your View_ID.
     JSONArray list = mainObj.getJSONArray("View");  // here is your view array.

    if(list != null){ for(int j = 0; j < list.length();j++){ JSONObject innerElem = list.getJSONObject(j); if(innerElem != null){ String button_id = innerElem.getString("Button_ID"); Toast.makeText(QRCode.this, button_id, Toast.LENGTH_SHORT).show(); } } } }