swifty json 解析数组对象

swifty json parse array object

如何将 Images 的数组设置为 Car class

images 变量

我的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 :

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 {[=12=]} 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 {[=13=]} as? [ImageItem]

不适合我

我认为问题在于您将其映射为图像项数组

imageItems = response["Images"].arrayObject.map {[=10=]} as? ImageItem

如果你想继续使用 SwiftyJSON,你可以向 ImageItem 添加一个初始化程序,它需要一个 JSON,就像你对 Car 所做的那样:

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"

尝试响应["图片"].arrayValue