如何从 Swift 中的 JSON 文件中读取混合类型数组? [英] How can I read in an array of mixed types from a JSON file in Swift?

查看:16
本文介绍了如何从 Swift 中的 JSON 文件中读取混合类型数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在 Xcode 中创建一个电影搜索应用程序,但在从 IMDB 的 API 读取 JSON 文件时遇到问题.

I am currently trying to create a movie search app in Xcode and am having trouble reading in the JSON file from IMDB's API.

API 示例:https://sg.media-imdb.com/建议/h/h.json

我可以读取几乎整个文件,除了图像信息 ('i'),它存储为一个数组,其中包含一个 URL(字符串)和两个可选的维度整数.

I can read in almost the entire file except for the image information ('i') which is stored as an array with a URL (string) and two optional ints for the dimensions.

   struct Response: Codable {
        var v: Int
        var q: String
        var d: [item]
    }
    
    struct item: Codable {
        var l: String
        var id: String
        var s: String
        var i: ??
    }

无论我为 'i' 输入什么类型,解析都会失败.我无法创建混合类型的数组,所以我很困惑如何继续.

No matter what type I enter for 'i' the parse fails. I can't create an array with mixed types so I am confused how to continue.

谢谢

推荐答案

你需要在这里做一些自定义解码.可以使用nestedUnkeyedContainer方法获取数组的编码容器,对数组元素进行一一解码.

You need to do some custom decoding here. You can use the nestedUnkeyedContainer method to get the coding container for the array, and decode the array elements one by one.

以下是实现 Decodable 的方法:

Here is how you would implement Decodable:

struct Response: Decodable {
     let v: Int
     let q: String
     let d: [Item]
 }
 
struct Item: Decodable {
    let l: String
    let id: String
    let s: String
    let url: String
    let width: Int?
    let height: Int?
    
    enum CodingKeys: CodingKey {
        case l, id, s, i
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        l = try container.decode(String.self, forKey: .l)
        id = try container.decode(String.self, forKey: .id)
        s = try container.decode(String.self, forKey: .s)
        var nestedContainer = try container.nestedUnkeyedContainer(forKey: .i)
        url = try nestedContainer.decode(String.self)
        width = try nestedContainer.decodeIfPresent(Int.self)
        height = try nestedContainer.decodeIfPresent(Int.self)
    }
}

您似乎不需要遵守 Encodable,所以我没有包含它,但是如果您需要,代码应该是相似的.

It doesn't seem like you need to conform to Encodable so I didn't include it, but the code should be similar if you ever need to.

这篇关于如何从 Swift 中的 JSON 文件中读取混合类型数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆