How to parse JSON structured-JSON Array Object in

2019-06-14 02:34发布

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.

3条回答
Animai°情兽
2楼-- · 2019-06-14 02:42

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.

查看更多
劫难
3楼-- · 2019-06-14 03:08

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.

查看更多
forever°为你锁心
4楼-- · 2019-06-14 03:09
 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);
查看更多
登录 后发表回答