ios - swifty json解析数组对象

标签 ios swift swifty-json

如何将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/

相关文章:

json - 使用 SwiftyJSON 的 Swift 可失败初始化器

ios - 用户是否应该添加到 XMPP 名册中才能开始消息传递?

ios - 我想在同一 View Controller 中显示更多照片

ios - GoogleToolboxForMac.framework 和 GoogleOpenSource.framework 冲突

swift - 具有显示关系的导航 Controller

json - 无法将数据从 JSON 响应快速加载到 ViewController 中

iOS:loadView 的推荐模式

ios - 在 Swift 中找出 Grand Central Dispatch 的语法

iOS WebKit 崩溃

ios - 休息 API : Cannot populate Tableview