使用Codable将复杂的json解码为没有嵌套结构的普通结构

时间:2018-02-13 12:44:29

标签: ios json swift

让我们有一个json

git reset --hard <your_commit_hash>

和结构:

{
    "channelId": 100,
    "channel_name": "STV 1",
        "stream": {
            "URL": "www.rtvs.sk",
            "DRM": "secureMedia",
            "drmKeys": ["1", "2", "3"],
            "userInfo": {
                "user": "Michal23",
                "userIsTester": true
            }
        }
}

我想从嵌套流中获取URL,但是没有为它创建嵌套结构。可能吗?怎么样?

1 个答案:

答案 0 :(得分:4)

查看documentation,您可以这样做,但它更像是一个手动过程。您需要解码嵌套容器,然后使用编码密钥提取信息。

//: Playground - noun: a place where people can play

import UIKit

let jsonData = """
{
    "channelId": 100,
    "channel_name": "STV 1",
    "stream": {
        "URL": "www.rtvs.sk"
    }
}
""".data(using: String.Encoding.utf8)!

struct Channel {
    var channelId : Int
    var channelName : String
    var channelUrl: URL

    private enum CodingKeys : String, CodingKey {
        case channelId
        case channelName = "channel_name"
        case stream
    }

    private enum AdditionalInfoKeys: String, CodingKey {
        case channelUrl = "URL"
    }
}

extension Channel: Decodable {
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        channelId = try values.decode(Int.self, forKey: .channelId)
        channelName = try values.decode(String.self, forKey: .channelName)

        let additionalInfo = try values.nestedContainer(keyedBy: AdditionalInfoKeys.self, forKey: .stream)
        channelUrl = try additionalInfo.decode(URL.self, forKey: .channelUrl)

    }
}

let decoder = JSONDecoder()
let channel = try? decoder.decode(Channel.self, from: jsonData)
print(channel)
  

OUTPUT:频道(channelId:100,channelName:“STV 1”,channelUrl:www.rtvs.sk))