下面是我的json响应和我需要构造的结构。
条件:我不想创建任何其他结构除了响应,媒体,并希望在单行解析如下所指定的。
{
"name": "xxxx",
"title": "xxxxxxx",
"assets": [
{
"items": [
{
"id": "eeee",
"desc": "rrrrrr"
}, {
"id": "eeee",
}, {
"desc": "rrrrrr"
}]
}]
}
struct Response {
let name : String
let title : string
let items : [Media]
private enum codingKeys : String, CodingKey {
case name = "name"
case title = "title"
case items = "assets.items"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: codingKeys.self)
name = try container.decode(String.self, forKey: .name)
title = try container.decode(TrayLayout.self, forKey: .title)
items = try container.decode([Media].self, forKey: .items)
}
}发布于 2020-02-11 16:53:30
找到了一种新的方法:
struct Media: Codable {
let id,desc: String?
enum CodingKeys: String, CodingKey {
case id,desc
}
}
struct Response: Decodable, CustomStringConvertible {
let name,title: String?
@NestedKey
let items: [Media]?
enum CodingKeys: String,NestableCodingKey {
case name,title,
case items = "assets/items"
}
}发布于 2020-01-29 23:25:56
我设法为你的问题找到了解决方案。
考虑以下是示例json
let jsonString = """
{
"name": "xxxx",
"title": "xxxxxxx",
"assets": [
{
"items": [
{
"id": "id11",
"desc": "desc11"
}, {
"id": "id12",
}, {
"desc": "desc13"
}]
},{
"items": [
{
"id": "id21",
"desc": "desc21"
}, {
"id": "id22",
}, {
"desc": "desc23"
}]
}]
}
"""您的结构将如下所示
struct Media: Codable {
let id,desc: String?
enum CodingKeys: String, CodingKey {
case id,desc
}
}
struct Response: Decodable {
let name,title: String?
let items: [Media]?
enum CodingKeys: String, CodingKey {
case name,title,items
case assets = "assets"
}
// Decoding
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
title = try container.decode(String.self, forKey: .title)
// Here as the assets contains array of object which has a key as items and then again consist of a array of Media we need to decode as below
let assets = try container.decode([[String:[Media]]].self, forKey: .assets)
// At this stage will get assets with a array of array so we first map and retrive the items and then reduce them to one single array
items = assets.compactMap{$0[CodingKeys.items.rawValue]}.reduce([], +)
}
}最后,我们可以按如下方式使用它
let data = jsonString.data(using: .utf8)!
let myResponse = try! JSONDecoder().decode(Response.self, from: data)现在您可以访问数据,如下所示
myResponse.name
myResponse.title
myResponse.items希望这段基本代码能帮助你实现你想做的事情。然后,您可以继续进行更多的嵌套解析。
我要感谢Nic Laughter的such a detailed article;通过参考,我设法提出了上面的解决方案。
发布于 2020-01-29 21:24:00
您可以尝试这样做:
struct Response: Decodable {
let name, title: String
let assets: [Assets]
}
struct Assets: Decodable {
let items: [Items]
}
struct Items: Decodable {
let id, desc: String
}然后你可以像这样解码它:
guard let response = try? JSONDecoder().decode(Response.self, from: data) else { print("Response not parsed"); return }https://stackoverflow.com/questions/59967964
复制相似问题