簡體   English   中英

如何在JAVA中解析此JSON響應

[英]How to Parse this JSON Response in JAVA

我想解析這些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"));
}
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 String的其他方法

    JSONObject obj= new JSONObject();
    JSONObject jsonObject = obj.fromObject(jsonString);
    ....

你可以做到:

JSONObject response = new JSONObject(resp);

然后你可以根據變量的類型使用:

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

要么

JSONArray tsm = response.getJSONArray(listTsm)

然后,如果你想遍歷內部的對象,你只需要使用for。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM