gpt4 book ai didi

ios - 可以在 Codable 中使用 NSArray 吗? (将 "Object Mapper"转换为 "Codable")

转载 作者:可可西里 更新时间:2023-11-01 01:49:11 39 4
gpt4 key购买 nike

我正在尝试将“Object Mapper”转换为“Codable”。我来自服务的响应包括 NSArray,其中包含自定义对象。我需要在 Codable 类中使用 NSArrayNSDictionary。但是,我失败了。我尝试使用像 AnyCodable 这样的第三方库,但是,我又失败了。我无法更改服务器端的响应。它必须以 Array 的形式出现。我必须使用数组。您有什么建议或信息吗?

class Person : Codable { //Error 1
var name: String?
var data: NSArray?

private enum CodingKeys : String, CodingKey {
case name
case data
}

func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(data, forKey: .data) //Error 2
}

func decode(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decode(String.self, forKey: .name)
self.data = try container.decode(NSArray.self, forKey: .data) //Error 3
}
}

Error 1: "Type 'Person' does not conform to protocol 'Decodable'"

Error 2: "Argument type 'NSArray' does not conform to expected type 'Encodable'"

Error 3: "Instance method 'decode(_:forKey:)' requires that 'NSArray' conform to 'Decodable'"

示例响应在这里。数组中的所有项目都不具有相同的内容。数组中的每一项都有不同的类型。

{
"data": [
{
"languageCode": "EN",
"deviceInformation": {
"screenSize": "height:812.0 width:375.0",
"connectionType": "wifi",
"deviceType": "iPhone",
"deviceCode": "D01D304C-D05C-4443-9A92-031C55D14XC7",
"operatingSystemVersion": "12.2",
"applicationVersion": "1.0"
},
"lastUpdatedParamDate": "13.05.2019 14:44:24",
"skipOptionalUpdate": 0
}
]
}

最佳答案

当你成功的时候

var data: NSArray?

这是一个桥接目标 - c 类型具有 Any 作为元素的类型,并且 Any 不符合 Codable 因此明确地将其设为类似

var data:[SomeModel]

或者使用 JSONSerialization 代替


struct Root: Codable {
let data: [Model]
}

struct Model: Codable {
let languageCode: String
let deviceInformation: DeviceInformation
let lastUpdatedParamDate: String
let skipOptionalUpdate: Int
}

struct DeviceInformation: Codable {
let screenSize, connectionType, deviceType, deviceCode: String
let operatingSystemVersion, applicationVersion: String
}

let eventData = try JSONDecoder().decode(Root.self, from: data) 

if you have more attributes you can add them , if some returns nil in some cases make them optional , but if the type changes then no way with Codable

关于ios - 可以在 Codable 中使用 NSArray 吗? (将 "Object Mapper"转换为 "Codable"),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56148126/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com