简体   繁体   中英

Decodable nested item in JSON with Swift

I am trying to decode some JSON I am getting from the reddit api. I want to create an array of objects from the data. The issue is I want to get the data but it is nested two levels deep.

This is the model

struct Moderator: Codable {
    var name: String
}

Here is the part in my network manager where it is trying to get the correct data. It keeps hitting the catch block:

    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let moderators = try decoder.decode([Moderator].self, from: data)
        completed(moderators, nil)
    } catch {
        completed(nil, "Invalid data")
    }

I am getting the json from here:

https://www.reddit.com/r/videos/about/moderators.json

A sample from it:

kind    "UserList"
data    
   children 
      0 
         name   "name3465"
         author_flair_text  null
         date   1297779059
         rel_id "rb_c32nl"
         id "t2_4d9s0"
         author_flair_css_class null
      1 
         name   "name2279"
         author_flair_text  null
         date   1300169101
         rel_id "rb_d151z"
         id "t2_1f8e1"
         author_flair_css_class null

As an example ModeratorResponse and Moderator would be the struct you wish to use in the app, and RawModerator is a private struct that hides the parsing that ignores the nested structures in between the data you are interested. Take a look at this example you can try on online.swiftplayground.run :

import Foundation

private struct RawModerator: Decodable {
    struct Data: Decodable {
        var children: [Moderator]
    }

    var kind: String
    var data: Data
}

struct ModeratorResponse: Decodable {
    var moderatorList: [Moderator]

    init(from decoder: Decoder) throws {
        let rawResponse = try RawModerator(from: decoder)
        moderatorList = rawResponse.data.children
    }
}

struct Moderator: Decodable {
    var name: String?
    var authorFlairTxt: String?
    var permissions: [String]?
    var date: Double?
    var rel_id: String
    var id: String
    var authorFlairCssClass: String?

    enum CodingKeys: String, CodingKey {
        case name = "name"
        case authorFlairTxt = "author_flair_text"
        case permissions = "mod_permissions"
        case date = "date"
        case rel_id = "rel_id"
        case id = "id"
        case authorFlairCssClass = "author_flair_css_class"
    }
}

let json = """
{
    "kind": "UserList", 
    "data": {
        "children": [
            {
                "name": "doug3465", 
                "author_flair_text": null, 
                "mod_permissions": ["all"], 
                "date": 1297779059.0, 
                "rel_id": "rb_c32nl", 
                "id": "t2_4d9s0", 
                "author_flair_css_class": null
            }, 

            {
                "name": "joka86", 
                "author_flair_text": null, 
                "mod_permissions": ["all"], 
                "date": 1571872041.0, 
                "rel_id": "rb_1k9iezh", 
                "id": "t2_36u6d", 
                "author_flair_css_class": null
            }
        ]
    }
}
""".data(using: .utf8)!

if let results = try? JSONDecoder().decode(ModeratorResponse.self, from: json) {
    for moderator in results.moderatorList {
        print("ID: \(moderator.id)")
        print("Name: \(moderator.name)")
    }
}

Which outputs:

 ID: t2_4d9s0 Name: Optional("doug3465") ID: t2_36u6d Name: Optional("joka86")

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