我有JSON类型的字典数组。如何使用可编码协议对其进行解码?

时间:2019-07-08 10:58:40

标签: swift rest api dictionary parsing

[
{
"status":"ok"
},
{
"feeds":[
{
"id":"68",
"userby":"1",
"usertype":"Registered    Students",
"content":"test",
"total_likes":"0",
"total_comments":"0",
"video_url":"(Some_URL)",
"image_url":"",
"created_date":"2019-06-26    20:34:02",
"modified_date":"0000-00-00    00:00:00",
"is_active":"Y",
"is_deleted":"N",
"feed_id":"68",
"user_name":"M    Y",
"profile_image":"(some_URL)",
"is_liked":"N"
}, //And so on feed entries...! ]}]    



// The Structure I tried using. 

typealias FeedDataDict = [FeedData]

struct FeedData : Codable {
    var status : String
    var feeds : [Feed]

}


let decoder = JSONDecoder()
let content = try decoder.decode( FeedDataDict.self , from: data)
print ( content[0].feeds[0].id )

我尝试将结构添加到数组,并使用索引0对其进行访问。但是它给我带来了麻烦,说索引的值被发现为零。

我希望收集数据中存在的所有值。

2 个答案:

答案 0 :(得分:0)

在我看来,您的json是一个字典数组,所以如果您这样做

do {
    let content = try JSONSerialization.jsonObject(with: data) as! [[String: Any]]
} catch {
    print(error)
}

然后content是一个数组,其中第一个索引包含["status": "ok"],第二个元素是feed数组

您还可以通过在Codable结构中使用自定义init来使用FeedData

struct FeedData : Codable {
    var status : String?
    var feeds : [Feed]?

    init(from decoder: Decoder) throws {
        var values = try decoder.unkeyedContainer()
        let statusDict = try values.decode([String:String].self)
        status = statusDict["status"]
        let feedsDict = try values.decode([String:[Feed]].self)
        feeds = feedsDict["feeds"]
    }
}

答案 1 :(得分:0)

我想在@Sh_Khan的答案中添加一些内容,即您的JSON数据格式正确,虽然可以使用,但格式应为

{
  "status": "ok",
  "feeds": [
    {
      "id": "68",
      "userby": "1",
      "usertype": "Registered    Students",
      "content": "test",
      "total_likes": "0",
      "total_comments": "0",
      "video_url": "https:\/\/medicalcosmetology.org.md-64.webhostbox.net\/adminpanel\/uploads\/feed\/videos\/V_20190514_1151392.mp4",
      "image_url": "",
      "created_date": "2019-06-26    20:34:02",
      "modified_date": "0000-00-00    00:00:00",
      "is_active": "Y",
      "is_deleted": "N",
      "feed_id": "68",
      "user_name": "M    Y",
      "profile_image": "https:\/\/medicalcosmetology.org.md-64.webhostbox.net\/adminpanel\/uploads\/user\/2eee0e67c31427fc5be42147ed9664b3.png",
      "is_liked": "N"
    }
  ]
}

一旦获得正确的JSON,然后尝试按以下方式进行解析:

let decoder = JSONDecoder()
let content = try decoder.decode( FeedDataDict.self , from: data)
print ( content.feeds[0].id )

但是,如果您不想更改它,请使用@Sh_Khan的答案。