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!