首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用可编编码将复杂的json解码为没有嵌套结构的平凡结构

使用可编编码将复杂的json解码为没有嵌套结构的平凡结构
EN

Stack Overflow用户
提问于 2018-02-13 12:44:29
回答 1查看 204关注 0票数 0

让我们来个json

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

还有一个结构:

代码语言:javascript
复制
struct Channel : Codable {
    var channelId : Int
    var channelName : String
    var channelUrl : URL

    private enum CodingKeys : String, CodingKey {
        case channelId
        case channelName = "channel_name"
        case channelUrl = "URL" <===??? json path somehow?
    }
}

我想从嵌套流中获取URL,但不为其创建嵌套结构。有可能吗?多么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-02-13 12:59:33

文档的角度来看,您可以这样做,但这更像是一个手动过程。您需要解码嵌套容器,然后使用编码键提取信息。

代码语言:javascript
复制
//: 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)

输出:频道(channelId: 100,channelName:"STV 1",channelUrl: www.rtvs.sk)

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48767142

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档