简体   繁体   中英

How to parse this JSON string

I'm trying to parse this string into java, but I keep getting errors.

{"id":1,"jsonrpc":"2.0","result":{"limits":{"end":3,"start":0,"total":3},"sources":[{"file":"/media/storage/media/re Music/","label":"re Music"},{"file":"/media/storage/media/ra Music/","label":"ra Music"},{"file":"addons://sources/audio/","label":"Music Add-ons"}]}}

When I use this code ...

String temp = //json code returned from up above
JSONObject obj = new JSONObject(temp);
JSONArray array = obj.getJSONArray("sources");

I get an error saying org.json.JSONObject Value... and then displays what is in temp. Any help?

The array named "sources" is several levels deep. You need to traverse down into the json.

Code formatters help with this stuff...

http://jsonformatter.curiousconcept.com/

{
   "id":1,
   "jsonrpc":"2.0",
   "result":{
      "limits":{
         "end":3,
         "start":0,
         "total":3
      },
      "sources":[
         {
            "file":"/media/storage/media/re Music/",
            "label":"re Music"
         },
         {
            "file":"/media/storage/media/ra Music/",
            "label":"ra Music"
         },
         {
            "file":"addons://sources/audio/",
            "label":"Music Add-ons"
         }
      ]
   }
}

It looks like the "sources" array is in the "result" object. So you would need to get that object and then get the array from that like this:

JSONObject obj = new JSONObject(temp);
JSONObject result = obj.getJSONObject("result");
JSONArray array = result.getJSONArray("sources");

Your json should have top level object, from there you need to get child objects. See this link for more detail.

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