简体   繁体   English

如何解析此JSON字符串

[英]How to parse this JSON string

I'm trying to parse this string into java, but I keep getting errors. 我正在尝试将此字符串解析为java,但我一直在收到错误。

{"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. 我收到一个错误说org.json.JSONObject Value ...然后显示temp中的内容。 Any help? 有帮助吗?

The array named "sources" is several levels deep. 名为“sources”的数组有几个级别。 You need to traverse down into the json. 你需要遍历json。

Code formatters help with this stuff... 代码格式化程序帮助这些东西......

http://jsonformatter.curiousconcept.com/ 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. 看起来“sources”数组位于“result”对象中。 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. 你的json应该有顶级对象,从那里你需要获得子对象。 See this link for more detail. 有关详细信息,请参阅此链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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