如何为 Imgur 创建模型对象 JSON | Swift

How to create model object for Imgur JSON | Swift

Imgur 图片搜索响应具有以下结构(简化):

{ "data": [  {"title" : "Kittens",
                "images" : [ { "title" : "",
                               "descripton" : "",
                               "nsfw" : "",
                               "link" : "https:\/\/i.imgur.com\/L1olKr1.jpg"
                          }, { "title" : "",
                                "descripton" : "",
                                "nsfw" : "",
                                "link" : "https:\/\/i.imgur.com\/L1olKr1.jpg" }]
                },{"title" : "Kittens",
                   "images" : [ { "title" : "",
                                  "descripton" : "",
                                  "nsfw" : "",
                                  "link" : "https:\/\/i.imgur.com\/L1olKr1.jpg"
                              }, { "title" : "",
                                   "descripton" : "",
                                   "nsfw" : "",
                                   "link" : "https:\/\/i.imgur.com\/L1olKr1.jpg" }]
          }]
   }

目标是为它创建一个模型。 我的尝试:

struct RawServerResponse: Decodable {
    
    // MARK: - ImageCategoy
    struct ImageCategory: Codable {
        let title: String
        let images: [Image]
    }

    // MARK: - Image
    struct Image: Codable {
        let title, descripton, nsfw: String
        let link: String
    }
    
    let data: [ImageCategory]
}

// We need to be getting an array of [ImageModel] as a result of decoding.

// Flattens nested json model to get data that only we need:
struct ImageModel: Decodable {
    let title: String
    let description: String
    let nsfw: String
    let link: String
    
    init(from decoder: Decoder) throws {
        let rawResponse = try RawServerResponse(from: decoder)
        
        title = rawResponse.data.first!.title
        description = rawResponse.data.first!.images.first!.descripton
        nsfw = rawResponse.data.first!.images.first!.nsfw
        link = rawResponse.data.first!.images.first!.link
        
    }

调用无效:

  let decodedImageModel : ImageModel = try JSONDecoder().decode(ImageModel.self, from: data)

我需要获取 [ImageModel] 数组。 请让我知道是否有更简单的方法从 imgur 响应中获取图像。


更新 1: 包含@Gereon 回复的最终答案。 注意:json 中的一些值最终变成了 null 而不是字符串。要处理这种情况,需要添加 'init' 方法,将空字符串赋给不存在的值:

import Foundation

struct ImgurResponse: Codable {
    let data: [ImageData]
}

struct ImageData: Codable {
    let title: String
    let images: [Image]
}

struct Image: Codable {
    let title, description, nsfw: String
    let link: String
    
    enum CodingKeys: String, CodingKey {
        case title
        case description
        case nsfw
        case link
    }
    
    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        title = try container.decodeIfPresent(String.self, forKey: .title) ?? ""
        description = try container.decodeIfPresent(String.self, forKey: .description) ?? ""
        nsfw = try container.decodeIfPresent(String.self, forKey: .nsfw) ?? ""
        link = try container.decodeIfPresent(String.self, forKey: .link) ?? ""
    }
}

更新 2:

或者,按照@Gereon 的建议,您可以将相应的属性标记为可选,例如 let link: String?。这使您可以摆脱手动 CodingKeys 和 init 实现。

无需创建重复的 ImageModel 结构,您可以直接从 API 响应中提取所需信息:

struct ImgurResponse: Codable {
    let data: [ImageData]
}

struct ImageData: Codable {
    let title: String
    let images: [Image]
}

struct Image: Codable {
    let title, descripton, nsfw: String
    let link: String
}

let response = try JSONDecoder().decode(ImgurResponse.self, from: data)

let images = response.data.flatMap { [=10=].images.compactMap { [=10=] }} // [Image]

型号

  struct RawServerResponse: Decodable {
        
        // MARK: - ImageCategoy
        struct ImageCategory: Codable {
            let title: String
            let images: [Image]
        }
    
        // MARK: - Image
        struct Image: Codable {
            let title, descripton, nsfw: String
            let link: String
        }
        
        let data: [ImageCategory]
    }
    
    // We need to be getting an array of [ImageModel] as a result of decoding.
    
    // Flattens nested json model to get data that only we need:
    struct ImageModel: Decodable {
        let title: String
        let description: String
        let nsfw: String
        let link: String
        
        
        init(title: String, desc: String, nsfw: String, link: String) {
            self.title = title
            self.description = desc
            self.nsfw = nsfw
            self.link = link
        }
    }
    
    struct ImageModels: Decodable {
        let arrObj:[ImageModel]
        
        init(from decoder: Decoder) throws {
            let rawResponse = try RawServerResponse(from: decoder)
            arrObj  = rawResponse.data.compactMap{ ImageModel(title: [=10=].title, desc: [=10=].images.first!.descripton, nsfw: [=10=].images.first!.nsfw, link: [=10=].images.first!.link)}
            /*var arr: [ImageModel] = []
            for imagecat in rawResponse.data{
                let model = ImageModel(title: imagecat.title, desc: imagecat.images.first!.descripton, nsfw: imagecat.images.first!.nsfw, link: imagecat.images.first!.link)
                arr.append(model)
            }
            
            arrObj = arr*/
        }
    }

正在解析

do{
                let serverData = try Data(contentsOf: data)
                let decodedImageModel : ImageModels = try JSONDecoder().decode(ImageModels.self, from: serverData)
                print("Response Success: \(decodedImageModel)")
            }catch{
                print("Error Data: \(error.localizedDescription)")
            }