How to Parse this JSON Response in JAVA

后端 未结 2 1441
轻奢々
轻奢々 2020-12-06 06:55

I want to parse these kind of Json responses :

{
\"MyResponse\": {
    \"count\": 3,
    \"listTsm\": [{
        \"id\": \"b90c6218-73c8-30bd-b532-5ccf435da7         


        
相关标签:
2条回答
  • 2020-12-06 07:35

    You can do simply:

    JSONObject response = new JSONObject(resp);
    

    Then you can use depending on the type of the variable something like:

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

    or

    JSONArray tsm = response.getJSONArray(listTsm)
    

    Then if you want to iterate through the objects inside you use just a for for it.

    0 讨论(0)
  • 2020-12-06 07:49
    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);
    }   
    }
    

    Output:

    [vignesh1, vignesh2, vignesh3]
    

    Comment: I didn't add validation

    [EDIT]

    other way to load json String

        JSONObject obj= new JSONObject();
        JSONObject jsonObject = obj.fromObject(jsonString);
        ....
    
    0 讨论(0)
提交回复
热议问题