这里我在 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]()
}
}
}
}
最佳答案
我建议使用这个很棒的 GIT 库来节省一些时间 ObjectMapper .它将帮助您对对象建模并将模型对象(类和结构)转换为 JSON,反之亦然。
关于ios - 如何在 swift 3 中为多个值实现模型类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47197737/