gpt4 book ai didi

ios - swifty json解析数组对象

转载 作者:行者123 更新时间:2023-12-01 19:30:21 27 4
gpt4 key购买 nike

如何将Images数组设置为images类的Car变量
我的json:

{
"Description": "test comment",
"GalleryId": 5548,
"ShortCode": "rzswig",
"Images": [
{
"Id": 9742,
"Link": "https://url/Images/5548/image9742_x560.jpg"
},
{
"Id": 9749,
"Link": "https://url/Images/5548/image9749_x560.jpg"
},
{
"Id": 9746,
"Link": "https://url/Images/5548/image9746_x560.jpg"
}
]
}
我的课 :
class Car: Hashable {
var shortCode: String
var description: String
var galleryId: Int
var imageItems: [ImageItem]?

init(response: JSON) {
shortCode = response["ShortCode"].stringValue
description = response["Description"].stringValue
galleryId = response["GalleryId"].intValue
imageItems = response["Images"].arrayObject.map {$0} as? [ImageItem]
}

init(shortCode: String, description: String, galleryId: Int, imageItems: [ImageItem]?) {
self.description = description
self.shortCode = shortCode
self.galleryId = galleryId
self.imageItems = imageItems
}
}

struct ImageItem {
var id: Int
var link: String
}
变体:
    imageItems = response["Images"].arrayObject.map {$0} as? [ImageItem]
对我不起作用

最佳答案

如果您想继续使用SwiftyJSON,则可以像使用ImageItem一样,在需要JSONCar中添加一个初始化程序:

init(response: JSON) {
id = response["Id"].intValue
link = response["Link"].stringValue
}
如果需要,您可能还想添加自动生成的成员明智的初始化程序。
然后,要初始化 imageItems,请执行以下操作:
imageItems = response["Images"].array?.map(ImageItem.init(response:))

如果您使用Swift内置的 Codable API,整个过程会容易得多。
只需将 CarImageItem都符合 Codable即可:
class Car: Codable {
var shortCode: String
var description: String
var galleryId: Int
var imageItems: [ImageItem]?

enum CodingKeys: String, CodingKey {
case shortCode = "ShortCode"
case description = "Description"
case galleryId = "GalleryId"
case imageItems = "Images"
}
}

struct ImageItem: Codable {
var id: Int
var link: String

enum CodingKeys: String, CodingKey {
case id = "Id"
case link = "Link"
}
}
然后执行此操作以反序列化json:
let car = JSONDecoder().decode(Car.self, data: jsonData) // jsonData is of type "Data"

关于ios - swifty json解析数组对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63167856/

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