本文介绍了如何在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')之外,我几乎可以读取整个文件.

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.

这是实现可解码的方法:

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文件中读取混合类型的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:22