How to parse this JSON response in Java

I want to parse these JSON responses:

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

I tried to use the simple JSON parser, but it didn't work for me:

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"));
}

Solution

public static void main(String[] args) throws JSONException {
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\"" + 
            "       }," + 
            "           \"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);
}   
}

Output:

[vignesh1,vignesh2,vignesh3]

Comment: I didn't add validation

[Edit]

Other methods of loading JSON string

JSONObject obj= new JSONObject();
    JSONObject jsonObject = obj.fromObject(jsonString);
    ....
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>