Using Codable With Nested JSON Is Both Easy And Fun!

Google Question: swift what is nestedContainer
https://medium.com/@nictheawesome/using-codable-with-nested-json-is-both-easy-and-fun-19375246c9ff

So Codable is new, fresh, and rad. But when I first started learning how to use it, I was surprised how little information there was available for people using nested JSON structures.

  • 所以Codable是新的,新鲜的,并且很棒。 但是当我第一次开始学习如何使用它时,我发现可用的信息很少对那些想要使用嵌套JSON结构的人。

TL;DR: just scroll to the bottom for the full code.

One StackOverflow answer even said you should encompass your model in another model for the server response, then just access your desired model via the initialized parent. Which is gross, don’t do that. (EDIT: sometimes this is appropriate, like if you’re parsing out several objects that all tie together and need to be initialized at the same time. I personally still don’t like it, but you do you.)

  • 一个StackOverflow回答甚至说你应该在另一个模型中包含你的模型用于服务器响应,然后只需通过初始化的父模型访问你想要的模型。 这是严重的,不要那样做。 (编辑:有时这是合适的,就像你解析出几个全部联系在一起并需要同时初始化的对象一样。我个人仍然不喜欢它,但是你做到了。)

So, I’m writing this to share with the world that getting at deeper levels of JSON data with Codable is both easy, and, as aforementioned, fun!

  • 所以,我写这篇文章是为了与全世界分享,用Codable获得更深层次的JSON数据既简单又如前所述,很有趣!

So first let’s just take a look at a simple model.

  • 首先让我们来看一个简单的模型。
struct Foo: Codable {
    let bar: Bool
    let baz: String
    let bestFriend: String
    let funnyGuy: String
    let favoriteWeirdo: String
}

As you can see, this is nothing too complicated. But what if we need to construct it from JSON data that looks like this?

  • 如你所见,这并不复杂。 但是,如果我们需要从看起来像这样的JSON数据构建它呢?
{"Response": {
    "Bar": true,
    "Baz": "Hello, World!",
    "Friends": {
        "Best": "Nic",
        "FunnyGuy": "Gabe",
        "FavoriteWeirdo": "Jer"
        }
    }
}

😱 Whatever shall we do?!

  • 😱无论我们做什么?!

Well, fortunately, Codable has some pretty nifty tricks up its sleeve, and it’s all built in for you! All you need to know is how to ask for it. First, let’s declare our CodingKeys enum inside our model so the API knows what keys we’re working with here, especially since they are different than the property names we want to be using.

  • 嗯,幸运的是,Codable有一些非常漂亮的技巧,而且它都是为你内置的! 您需要知道的是如何使用它。 首先,让我们在模型中声明我们的CodingKeys枚举,以便API知道我们在这里使用的键,特别是因为它们与我们想要使用的属性名称不同。
enum CodingKeys: String, CodingKey {
    case response = "Response"
    case bar = "Bar"
    case baz = "Baz"
    case friends = "Friends"
    case bestFriend = "Best"
    case funnyGuy = "FunnyGuy"
    case favoriteWeirdo = "FavoriteWeirdo"
}

A quick note on the naming convention here: You can name these cases anything you want, but unless you’re going to declare the values explicitly, they need to perfectly match the keys in the JSON data. So just to clarify, if you’re providing the values, you can name them whatever you’d like, but you have the option of simply naming them exactly as they come back in the JSON tree and save yourself some work.

  • 关于命名约定的快速说明:您可以将这些情况命名为您想要的任何名称,但除非您要明确声明这些值,否则它们需要与JSON数据中的键完全匹配。 所以只是为了澄清一下,如果你提供了这些值,你可以随心所欲地命名它们,但你可以选择简单地命名它们,就像它们回到JSON树中一样,并且你也可以省点事。

You’ll also notice that we have declared keys for everything in our tree. Let’s take a look at how to build our model using our data and CodingKeys!

  • 您还会注意到我们已经为树中的所有内容声明了键。 我们来看看如何使用我们的数据和CodingKeys构建我们的模型!
init(from decoder: Decoder) throws {
    let container = try decoder.container(keyedBy: CodingKeys.self)
    let response = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .response)
    bar = try response.decode(Bool.self, forKey: .bar)
    baz = try response.decode(String.self, forKey: .baz)
    let friends = try response.nestedContainer(keyedBy: CodingKeys.self, forKey: .friends)
    bestFriend = try friends.decode(String.self, forKey: .bestFriend)
    funnyGuy = try friends.decode(String.self, forKey: .funnyGuy)
    favoriteWeirdo = try friends.decode(String.self, forKey: .favoriteWeirdo)
}

Whew! Let’s break this down. First, the container is basically our root of the JSON tree we’re working with here. Think of it as the outer-most set of brackets. Knowing that, it makes sense why we need to get to the response (by the key of “Response”), because technically that is already nested within our root container! After that it’s a breeze to get Bar and Baz out, but here comes another container! This is where the brilliance of this API really shines through: you just tell it you need another nested container! With Friends there, we can safely and easily access our last properties.

  • 呼! 让我们打破这个。 首先,容器基本上是我们在这里使用的JSON树的根。 可以把它想象成最外面的括号。 知道了,为什么我们需要得到响应(通过“响应”的键)是有道理的,因为技术上已经嵌套在我们的根容器中! 在那之后,让Bar和Baz退出是一件轻而易举的事,但这里有另一个容器! 这就是这个API的亮点真正发挥作用的地方:你只需告诉它你需要另一个嵌套容器! 有了朋友,我们可以安全轻松地访问我们的最后一个属性。

Piece of 🍰, right?!

  • 一块🍰,对吧?!

Now, let’s take a look at how we take our pretty model and turn it into Data that we can send back to the server!

  • 现在,让我们来看看我们如何采用我们的漂亮模型并将其转换为可以发送回服务器的数据!
func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    var response = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .response)
    try response.encode(bar, forKey: .bar)
    try response.encode(baz, forKey: .baz)
    var friends = response.nestedContainer(keyedBy: CodingKeys.self, forKey: .friends)
    try friends.encode(bestFriend, forKey: .bestFriend)
    try friends.encode(funnyGuy, forKey: .funnyGuy)
    try friends.encode(favoriteWeirdo, forKey: .favoriteWeirdo)
}

As you can see, you just follow the same steps! Set up the base container, then get to your Response nested container. Throw in your top-level properties, then get the nested container for your friends. Throw those in there, and voila! You’re now a master of handling nested dictionaries in a JSON tree with Codable!

  • 如您所见,您只需按照相同的步骤操作即可! 设置基本容器,然后转到Response嵌套容器。 扔进您的顶级属性,然后为您的朋友获取嵌套容器。 把那些扔进那里,瞧! 您现在是使用Codable在JSON树中处理嵌套字典的大师!

Now that you’re a pro, take it to the next level! 👇🏻

  • 既然你是专业人士,那就把它提升到一个新的水平!👇🏻

Here’s the code you can throw into a playground to see how it all works together:

  • 这是你可以扔进游乐场的代码,看看它们是如何一起工作的:
let jsonString = """
{"Response": {
    "Bar": true,
    "Baz": "Hello, World!",
    "Friends": {
        "Best": "Nic",
        "FunnyGuy": "Gabe",
        "FavoriteWeirdo": "Jer"
        }
    }
}
"""
let data = jsonString.data(using: .utf8)!

struct Foo: Codable {
    // MARK: - Properties
    let bar: Bool
    let baz: String
    let bestFriend: String
    let funnyGuy: String
    let favoriteWeirdo: String
    // MARK: - Codable
    // Coding Keys
    enum CodingKeys: String, CodingKey {
        case response = "Response"
        case bar = "Bar"
        case baz = "Baz"
        case friends = "Friends"
        case bestFriend = "Best"
        case funnyGuy = "FunnyGuy"
        case favoriteWeirdo = "FavoriteWeirdo"
    }
    // Decoding
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let response = try container.nestedContainer(keyedBy: CodingKeys.self, forKey: .response)
        bar = try response.decode(Bool.self, forKey: .bar)
        baz = try response.decode(String.self, forKey: .baz)
        let friends = try response.nestedContainer(keyedBy: CodingKeys.self, forKey: .friends)
        bestFriend = try friends.decode(String.self, forKey: .bestFriend)
        funnyGuy = try friends.decode(String.self, forKey: .funnyGuy)
        favoriteWeirdo = try friends.decode(String.self, forKey: .favoriteWeirdo)
    }
    // Encoding
    func encode(to encoder: Encoder) throws {
        var container = encoder.container(keyedBy: CodingKeys.self)
        var response = container.nestedContainer(keyedBy: CodingKeys.self, forKey: .response)
        try response.encode(bar, forKey: .bar)
        try response.encode(baz, forKey: .baz)
        var friends = response.nestedContainer(keyedBy: CodingKeys.self, forKey: .friends)
        try friends.encode(bestFriend, forKey: .bestFriend)
        try friends.encode(funnyGuy, forKey: .funnyGuy)
        try friends.encode(favoriteWeirdo, forKey: .favoriteWeirdo)
    }
}
let myFoo = try! JSONDecoder().decode(Foo.self, from: data)
// Initializes a Foo object from the JSON data at the top.
let dataToSend = try! JSONEncoder().encode(myFoo)
// Turns your Foo object into raw JSON data you can send back!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容