我有一个Web服务,它返回以下格式的通用JSON结构
{
"status" : "failure",
"message": "Unauthorized",
"payload" : []//could be object array depending on service end-point
}
在上面,"有效载荷"可以有任何Object Array。在我的情况下可以说它将返回[Book]或[Page],这取决于我所调用的服务。
现在我创建了三个模型Result,Book,Page如下
class Book {
public var id : Int = 0
public var bookName : String = ""
required public init?(dictionary: [String:Any]) {
id = dictionary["id"] as! Int
bookName = dictionary["bookName"] as! String
}
public class func modelsFromArray(array:NSArray) -> [Book]
{
var models:[Book] = []
for item in array
{
models.append(Book(dictionary: item as! [String:Any])!)
}
return models
}
}
class Page {
public var id : Int = 0
public var pageName : String = ""
required public init?(dictionary: [String:Any]) {
id = dictionary["id"] as! Int
pageName = dictionary["pageName"] as! String
}
public class func modelsFromArray(array:NSArray) -> [Page]
{
var models:[Page] = []
for item in array
{
models.append(Page(dictionary: item as! [String:Any])!)
}
return models
}
}
class Result {
public var status : String = ""
public var message : String = ""
public var payload : Array<Any> // is this correct Any or AnyObject ?
// here below i need help so that i can pass Class type and then use it
required public init?<T>(dictionary: [String:Any], type : T.Type) {
status = dictionary["status"] as! String
message = dictionary["message"] as! String
if (dictionary["payload"] != nil) { payload = type.modelsFromArray(array:dictionary["payload"] as! NSArray ) // this is compiler error (Type T has no member modelsFromArray). How can i do here so that every time i pass in Class type or any thing on which i can initialize this class object with proper payload object.
}
}
这是我想如何使用上面的类。下面是获取Book end-point
的代码示例let jsonResponse = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String:Any]
result = Result(dictionary: jsonResponse , Book.self // or Book or what?)!
如果有人能以任何其他最好的方式指导我这样做,我将不胜感激
谢谢:)
答案 0 :(得分:-1)
你可以这样试试。
if type == Book.self {
if (dictionary["payload"] != nil) { payload = Book.modelsFromArray(array:dictionary["payload"] as! NSArray )
}
} else {
if (dictionary["payload"] != nil) { payload = Page.modelsFromArray(array:dictionary["payload"] as! NSArray )
}
}