加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

数组 – Swift 4 JSON Codable – 返回的值有时是一个对象,其他

发布时间:2020-12-14 04:39:57 所属栏目:百科 来源:网络整理
导读:我从API获取的数据返回单个对象,但是当有多个对象时,它会在同一个键中返回一个数组.使用我正在使用的当前模型(struct),当阵列出现时解码失败. 这些结果是随机排序的,这意味着我无法知道何时会为对象或数组提供服务. 有没有办法创建一个模型来考虑这个事实,并
我从API获取的数据返回单个对象,但是当有多个对象时,它会在同一个键中返回一个数组.使用我正在使用的当前模型(struct),当阵列出现时解码失败.

这些结果是随机排序的,这意味着我无法知道何时会为对象或数组提供服务.

有没有办法创建一个模型来考虑这个事实,并可以为值(‘String’或'[String]’)分配正确的类型,以便解码继续没有问题?

这是返回对象的示例:

{
    "firstFloor": {
        "room": "Single Bed"
    }
}

这是返回数组的示例(对于相同的键):

{
    "firstFloor": {
        "room": ["Double Bed","Coffee Machine","TV","Tub"]
    }
}

应该能够用作解码上述两个示例的模型的结构示例:

struct Hotel: Codable {
    let firstFloor: Room

    struct Room: Codable {
        var room: String // the type has to change to either array '[String]' or object 'String' depending on the returned results
    }
}

这些结果是随机排序的,这意味着我无法知道何时会为对象或数组提供服务.

这是完整的游乐场文件:

import Foundation

// JSON with a single object
let jsonObject = """
{
    "firstFloor": {
        "room": "Single Bed"
    }
}
""".data(using: .utf8)!

// JSON with an array instead of a single object
let jsonArray = """
{
    "firstFloor": {
        "room": ["Double Bed","Tub"]
    }
}
""".data(using: .utf8)!

// Models
struct Hotel: Codable {
    let firstFloor: Room

    struct Room: Codable {
        var room: String // the type has to change to either array '[String]' or object 'String' depending on the results of the API
    }
}

// Decoding
let decoder = JSONDecoder()
let hotel = try decoder.decode(Hotel.self,from: jsonObject) //

print(hotel)

解决方法

您可以使用Enum with Associated Values(在本例中为String和Array)来封装结果的歧义,例如:

enum MetadataType: Codable {
    case array([String])
    case string(String)

    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        do {
            self = try .array(container.decode(Array.self))
        } catch DecodingError.typeMismatch {
            do {
                self = try .string(container.decode(String.self))
            } catch DecodingError.typeMismatch {
                throw DecodingError.typeMismatch(MetadataType.self,DecodingError.Context(codingPath: decoder.codingPath,debugDescription: "Encoded payload not of an expected type"))
            }
        }
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        switch self {
        case .array(let array):
            try container.encode(array)
        case .string(let string):
            try container.encode(string)
        }
    }
}

struct Hotel: Codable {
    let firstFloor: Room

    struct Room: Codable {
        var room: MetadataType
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读