7

我想解析这些 Json 响应:

{
"MyResponse": {
    "count": 3,
    "listTsm": [{
        "id": "b90c6218-73c8-30bd-b532-5ccf435da766",
        "simpleid": 1,
        "name": "vignesh1"
    },
    {
        "id": "b90c6218-73c8-30bd-b532-5ccf435da766",
        "simpleid": 2,
        "name": "vignesh2"
    },
    {
        "id": "b90c6218-73c8-30bd-b532-5ccf435da766",
        "simpleid": 3,
        "name": "vignesh3"
    }]
 }
}

我尝试使用 SIMPLE JSON 解析器,但这对我不起作用:

Object obj = parser.parse(resp);
JSONObject jsonObject = (JSONObject) obj;
JSONArray response = (JSONArray) jsonObject.get("MyResponse");

//JSONArray arr=new JSONArray(yourJSONresponse);
ArrayList<String> list = new ArrayList<String>();
for(int i=0; i<response.size(); i++){
    list.add(response.get(i)("name"));
}
4

2 回答 2

25
public static void main(String[] args) throws JSONException {
    String jsonString  = "{" + 
            "   \"MyResponse\": {" + 
            "       \"count\": 3," + 
            "       \"listTsm\": [{" + 
            "           \"id\": \"b90c6218-73c8-30bd-b532-5ccf435da766\"," + 
            "           \"simpleid\": 1," + 
            "           \"name\": \"vignesh1\"" + 
            "       }," + 
            "       {" + 
            "           \"id\": \"b90c6218-73c8-30bd-b532-5ccf435da766\"," + 
            "           \"simpleid\": 2," + 
            "           \"name\": \"vignesh2\"" + 
            "       }," + 
            "       {" + 
            "           \"id\": \"b90c6218-73c8-30bd-b532-5ccf435da766\"," + 
            "           \"simpleid\": 3," + 
            "           \"name\": \"vignesh3\"" + 
            "       }]" + 
            "   }" + 
            "}";


    JSONObject jsonObject = new JSONObject(jsonString);
    JSONObject myResponse = jsonObject.getJSONObject("MyResponse");
    JSONArray tsmresponse = (JSONArray) myResponse.get("listTsm");

    ArrayList<String> list = new ArrayList<String>();

    for(int i=0; i<tsmresponse.length(); i++){
        list.add(tsmresponse.getJSONObject(i).getString("name"));
    }

    System.out.println(list);
}   
}

输出:

[vignesh1, vignesh2, vignesh3]

评论:我没有添加验证

[编辑]

加载json字符串的其他方式

    JSONObject obj= new JSONObject();
    JSONObject jsonObject = obj.fromObject(jsonString);
    ....
于 2013-09-19T15:50:38.610 回答
-1

你可以简单地做:

JSONObject response = new JSONObject(resp);

然后您可以根据变量的类型使用,例如:

int count = response.getint("count");

或者

JSONArray tsm = response.getJSONArray(listTsm)

然后,如果您想遍历内部的对象,只需使用 for 即可。

于 2017-11-29T11:03:58.183 回答