简体   繁体   中英

How to parse this type of JSON in Java?

How do I fetch the third leaveTypeId and year from leaveInfo?

{  
"statusCode":"1001",
"message":"Success",
"response":{  
  "leaveInfo":[  
     {  

        "leaveTypeId":1,
        "year":2014

     },
     {  

        "leaveTypeId":2,
        "year":2014

     },
     {  
        "leaveTypeId":3,
        "year":2014,

     },
     {  
        "leaveTypeId":4,
        "year":2014
     },
     {  
        "leaveTypeId":5,
        "year":2014
     },
     {  
        "leaveTypeId":6,
        "year":2014
     }
  ]
}
}

I did this to achieve my need

JSONObject jobj1 = new JSONObject(result);
String statusCode = jobj1.getString("statusCode");
if (statusCode.equalsIgnoreCase("1001"))
{
    String response = jobj1.getString("response");
    JSONObject jobj2 = new JSONObject(response);
    String leaveInfo = jobj2.getString("leaveInfo");
    System.out.println("leaveInfo: "+leaveInfo);
}

I don't know how to go further as there are no key values for the arrays inside leaveInfo. Please help me in this regard.

Use this

JSONObject jobj1 = new JSONObject(result);
String statusCode = jobj1.getString("statusCode");
if (statusCode.equalsIgnoreCase("1001"))
{
 String response = jobj1.getString("response");
 JSONObject jobj2 = new JSONObject(response);
 JSONArray ary=jobj2.getJSONArray("leaveInfo");
 for(int i=0;i<ary.length;i++){
 JSONObject obj=ary.getJSONObject(i);
 String leaveInfo=obj.getString("leaveTypeId");
 System.out.println("leaveInfo: "+leaveInfo);
 } 

 }

I hope this will help to you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM