【问题标题】:How do I use Codable to parse this JSON?如何使用 Codable 解析这个 JSON?
【发布时间】:2018-12-29 08:29:59
【问题描述】:

我一直在尝试从我的 JSON 解析这个对象并不断收到这个错误:

“错误:类型不匹配(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "预期解码 Array 但找到了字典。", 底层错误:nil))\n"

如果我从这里删除数组括号let video = try decoder.decode([Content].self, from: data),则会收到一条错误消息:

"错误: keyNotFound(CodingKeys(stringValue: "description", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "没有与键 CodingKeys 关联的值(stringValue: \"description\", intValue: nil) (\"description\").", underlyingError: nil))\n"

我怎样才能让它消失?这是我的JSON 和代码:

    JSON: 

        > {     "content": [{
        >              "description": "Hello",
        >              "category": "World wides",
        >              "creator": {
        >              "name": "The One",
        >              "site": "Purple",
        >              "url": "http://www.sample.com"
        >              },
        >              "time": 300,
        >              "full": "https:sample2.com",
        >              "clothes": "jacket",
        >              }] 
           }


struct Content: Decodable {
    let description: String
    let category: String
}


if let fileURL = Bundle.main.url(forResource: "stub", withExtension: "json") {
    do {
        let data = try Data(contentsOf: fileURL)

        let decoder = JSONDecoder()
        let video = try decoder.decode([Content].self, from: data)

        print(video.description)

        // Success!
       // print(content.category)
    } catch {
        print("Error: \(error)")
    }
} else {
    print("No such file URL.")
}

【问题讨论】:

  • let video = try decoder.decode([Content].self, from: data)更改为let video = try decoder.decode(Content.self, from: data)
  • 当我这样做时,我收到一条错误消息:“错误:keyNotFound(CodingKeys(stringValue:“description”,intValue:nil),Swift.DecodingError.Context(codingPath:[],debugDescription: "没有与键 CodingKeys 关联的值(stringValue: \\"description\\", intValue: nil) (\\"description\\").", underlyingError: nil))\n"

标签: ios json iphone swift codable


【解决方案1】:

在您的 JSON 数据中,content 包含单个元素的数组。

我建议您像这样创建结构:

struct Response: Decodable {
  let content: [Item]
}

struct Item: Decodable {
  let description: String
  let category: String
}

然后你可以像这样解码并使用它:

let response = try decoder.decode(Response.self, from: data)
guard !response.content.isEmpty else { // error handling here }
let video = response.content[0]

【讨论】:

  • 我仍然收到一条错误消息:“错误:keyNotFound(CodingKeys(stringValue: "content", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value关联键 CodingKeys(stringValue: \\"video\\", intValue: nil) (\\"video\\").", underlyingError: nil))\n"
【解决方案2】:

缺少对应的根对象结构,它是一个字典 ({}),键为 content

这解释了两个错误消息(对象是字典,没有键 description)。

content 的值是一个数组,因此您需要一个循环来迭代项目。

struct Root : Decodable {
    let content : [Content]
}

struct Content: Decodable {
    let description: String
    let category: String
}

...

let root = try decoder.decode(Root.self, from: data)
let content = root.content
for item in content {
    print(item.description)
}

【讨论】:

    猜你喜欢
    • 2021-09-05
    • 1970-01-01
    • 2020-05-30
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多