简体   繁体   中英

How to parse JSON structured-JSON Array Object in Java

i'm trying to parse this JSON code

{
  "resultCode":"350",
  "message":"OK",
  "result":1,
  "data":
{
    "totalCount":"2",
    "videos":[
      {
        "videoId":"73bfedf534",
        "VideoUrl":"www.videourlexample.com",
        "title":"vbsample1",
        "description":""
      },

{
        "videoId":"73bfedf534",
        "VideoUrl":"www.videourlexample.com",
        "title":"vbsample2",
        "description":""
      }
    ]
  }
}

I was able to parse only this.

"resultCode":"350",
"message":"OK",
"result":1,

this is the java code

JSONObject jsonObject = (JSONObject)  
//return the JSON code above.
jsonParser.parse(getHTML("...httpRequest..."));

    // get a String from the JSON object
    String resultCode = (String) jsonObject.get("resultCode");
    System.out.println("[RESULTCODE] The message is: " + resultCode);


    // get a String from the JSON object
    String message = (String) jsonObject.get("message");
    System.out.println("[MESSAGE] The message is: " + message);

    // get a number from the JSON object
    long result =  (long) jsonObject.get("result");
    System.out.println("[RESULT] The resultCode is: " + result);

I can't parse the "data". Someone can help me? I would like to take each value from the json array separately... like resultCode, message and result.

Thank you.

 JSONObject mainObj= new JSONObject(yourJSON);
 String resultCode= mainObj.get("resultCode");
 String message= mainObj.get("message");
 String result= mainObj.get("result");
 JSONObject dataObj = mainObj.get("data");
 JSONArray jsonArray = (JSONArray) dataObj.get("videos");
 for (int i = 0; i <jsonArray.length(); i++) {
   JSONObject obj= jsonArray.get(i);
   String videoId=obj.get("videoId");
   String videoUrl=obj.get("VideoUrl");
   String title=obj.get("title");
   String description=obj.get("description");
    System.out.println("videoId="+videoId   +"videoUrl="+videoUrl+"title=title"+"description="+description);        
}
 System.out.println("resultCode"+resultCode+"message"+message+"result"+result);

You can try using this:-

JSONObject dataObj = (JSONObject)dataObj .get("data");
JSONArray jsonArray = (JSONArray) dataObj.get("videos");
for (int i = 0; i <jsonArray.length(); i++) {
   System.out.println(((JSONObject)jsonArray.get(i)).get("videoUrl"));
}

Currently I have just printes videoUrl, you can similarly get other attributes for videos.

for data use:

int totalCount = (int) ((Map) jsonObject.get("data")).get("totalCount");

JSONArray videos = (JSONArray) jsonObject.get("data")).get("videos");

and then parse videos JSONArray.

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