使用 org.json 解析 JSON

2022-09-02 05:37:31

我正在尝试解析来自如下所示的服务器的输出:

{
  "GetFolderFilesByZoneResult": [
    {
      "ID": 98748,
      "CreatedBy": "",
      "UpdatedBy": "none",
      "CreatedDate": "\/Date(1308273033620+0100)\/",
      "UpdatedDate": "\/Date(1308303003770+0100)\/",  
      "CommentCount": 0,
      "Key": "",
      "Enabled": true,
      "MimeType": "video",
      "Votes": 2,
      "TotalRating": 0,
      "AllowComments": true,
      "ViewCount": 323,
      "ReleaseDate": "\/Date(1308273000000+0100)\/",
      "ExpireDate": "\/Date(4102444800000+0000)\/",
      "Author": "",
      "Size": 133799936,
      "Tag1": "",
      "Tag2": "",
      "Tag3": "",
      "RecycleBin": false
    },
    {
      "ID": 99107,
      "CreatedBy": "",
      "UpdatedBy": "none",
      "CreatedDate": "\/Date(1308583412520+0100)\/",
      "UpdatedDate": "\/Date(1308583564007+0100)\/",     
      "CommentCount": 0,
      "Key": "",
      "Enabled": true,
      "MimeType": "video",
      "Votes": 0,
      "TotalRating": 0,
      "AllowComments": true,
      "ViewCount": 33,
      "ReleaseDate": "\/Date(1308583380000+0100)\/",
      "ExpireDate": "\/Date(4102444800000+0000)\/",
      "Author": "",
      "Size": 47955968,
      "Tag1": "",
      "Tag2": "",
      "Tag3": "",
      "RecycleBin": false
    }
  ]
}

我正在尝试使用Java org.json来解析它,但我没有任何JSON / org.json的经验,所以我遇到了一点麻烦。如何解析此内容?


答案 1

1)假设你的路径上有JSON库(从 www.json.org),这很容易。

import org.json.JSONTokener;
...

URI uri = new URI("http://someserver/data.json");
JSONTokener tokener = new JSONTokener(uri.toURL().openStream());
JSONObject root = new JSONObject(tokener);

从那里,您可以解决 JSON 对象的各个部分。查看 Javadocs 以了解具体细节。https://developer.android.com/reference/org/json/package-summary.html


答案 2

以下是最通用的解决方案,它允许将任何JSON类型解析为适当的Java类型:

Object json = new JSONTokener(response).nextValue();

然后,您可以确定结果类型并对其进行适当的处理。