簡體   English   中英

如何在Swift 3中為多個值實現模型類?

[英]How to implement model class for multiple values in swift 3?

在這里,我在JSON中具有value ,其中多個鍵值對中的某些返回字符串,對於某些鍵返回中的數組,其中第一個字典的自定義屬性數組中的value鍵值對中存在的數據不同,第二個字典中的數據不同value鍵值對在這里是不同的,那么如何為不同鍵值的內部數組實現模型類?

struct MediaGallery {

    let id : Int
    let mediaType : String
    let label : Any
    let position : Int
    let disabled : Any
    let file : String

    init(dict : [String:Any]) {
        self.id = (dict["id"] as? Int)!
        self.mediaType = (dict["media_type"] as? String)!
        self.label =  dict["label"]!
        self.position = (dict["position"] as? Int)!
        self.disabled = dict["disabled"]!
        self.file = (dict["file"] as? String)!
    }
}
struct AttributeList {

    let label : String
    let value : String
    let code : String

    init(dict : [String:Any]){

        self.label = (dict["label"])! as! String
        self.value = (dict["value"])! as! String
        self.code = (dict["code"])! as! String
    }
}
struct DetailsListAttribute {

    let attributeCode : String
    let value : Any

    init?(dict : [String:Any]) {

        self.attributeCode = dict["attribute_code"] as! String
        print(self.attributeCode)
        if let values = dict["value"] as? String {
            self.value = values
        }
        else {
            if let arr = dict["value"] as? [[String:Any]]{
                var filterArr = [AttributeList]()
                for obj in arr {
                    filterArr.append(AttributeList(dict: obj))
                }
                self.value = filterArr
            } else {
                self.value = [AttributeList]()
            }
        }

    }
}

我嘗試了Tj3n注釋中提到的多個JSON映射框架。 他們都有優點和缺點。 蘋果建議您遵循此處給出的建議。 另外,您應該檢查可Codable協議(需要swift 4)。

我建議您使用這個很棒的GIT庫ObjectMapper節省一些時間。 它將幫助您建模對象並將模型對象(類和結構)轉換為JSON,反之亦然。

好的,我沒有完整的JSON,對我來說似乎也不是很清楚。

但是這里是您如何使用Codable協議在Swift中輕松解析和創建模型Class的方法。

您可以閱讀有關它的更多信息和/或一些示例教程: Ultimate Guide

簡而言之,什么是Codable協議?

您不再需要第三方庫來解析並將json數據設置為模型類。 您只需創建代表JSON的類即可。 並根據鍵名為您創建類,屬性和所有內容。

這是您的JSON的示例,我不知道我是否了解您的JSON格式,但是您可以找到竅門:

struct Response: Codable {
    let ca: [CustomAttribute]?

    enum CodingKeys: String, CodingKey {
        case ca = "custom_attributes"
    }
}

struct CustomAttribute: Codable {
    let code: String?
    let value: [Value]?

    struct Value: Codable {
        let label: String?
        let value: String?
        let code: String?

        let avg: String?  // I don't know how your value array is composed
        let count: Int?   // I don't know how your value array is composed
    }

    enum CodingKeys: String, CodingKey {
        case code = "attribute_code"
        case avg = "avg_rating_percent"
    }
}

對我來說,看起來像那樣。

我看不到整個JSON,但是假設您擁有整個JSON作為Response Struct,它包含多個對象,例如CustomAttribute Array。 然后,您可以定義CustomAttribute結構,並添加與JSON一樣多的屬性。

無論如何,您可以這樣稱呼:

當您收到來自API調用的響應時,可以執行以下操作:

if let data = response.data {
         let decoder = JSONDecoder()
         let response = try! decoder.decode(Response.self, from: data)
         print("Only printing the Custom Attribute : \(response.ca!)")
} 

我將整個json數據解碼為對象響應(例如我的Struct)。 然后傳遞給我的響應回調,或者

這可能會晚了,但我認為這會幫助其他人

模型類因SwiftyJSON,簡單swift類,Gloss或swift可編碼(Swift 4)等框架而異。 您可以使用自定義jsoncafe.com輕松在線生成模型類

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM