根据文章http://www.weheartswift.com/swift-objc-magic/ 我创建了一个NSObject扩展来将JSON字符串解析为对象
import Foundation
extension NSObject {
class func fromJson(jsonInfo: NSDictionary) -> Self {
var object = self()
(object as NSObject).load(jsonInfo)
return object
}
func load(jsonInfo: NSDictionary) {
for (key, value) in jsonInfo {
let keyName = key as String
if (respondsToSelector(NSSelectorFromString(keyName))) {
setValue(value, forKey: keyName)
}
}
}
func propertyNames() -> [String] {
var names: [String] = []
var count: UInt32 = 0
var properties = class_copyPropertyList(classForCoder, &count)
for var i = 0; i < Int(count); ++i {
let property: objc_property_t = properties[i]
let name: String = String.fromCString(property_getName(property))!
names.append(name)
}
free(properties)
return names
}
func asJson() -> NSDictionary {
var json:Dictionary<String, AnyObject> = [:]
for name in propertyNames() {
if let value: AnyObject = valueForKey(name) {
json[name] = value
}
}
return json
}
}
我创建了一个继承NSObject的类
import Foundation
class Weather : NSObject {
var date : String = ""
var currentCity : String = ""
var weather : String = ""
var wind : String = ""
var dayPictureUrl : String = ""
var nightPictureUrl : String = ""
var temperature : String = ""
}
然后我构建一个帮助程序来获取API并将结果解析为Object
func requestApi(url :String, returnType: AnyClass, success: (res: AnyObject)->() ){
var queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
var group = dispatch_group_create()
dispatch_group_async(group, queue) { () -> Void in
var url = NSURL.init(string:url)
var data = NSData.init(contentsOfURL:url!)
let jsonObj: AnyObject? = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments,error:nil)
if let topDict = jsonObj as? NSDictionary {
var obj : AnyObject = returnType.fromJson(topDict)
success(res: obj);
}
}
}
var api : String = "http://somesite.com/jsonapi"
requestApi(api, Weather.self, { (res) -> () in
// finish get the res obj
})
我知道如何使用Objective-C 但是Swift我在这一行得到了这个错误
LINE : var obj : AnyObject = returnType.fromJson(topDict)
ERROR : 'AnyClass' does not h``ave a member named from JSON
我对Swift一无所知, 我只想调用returnType类函数, 我怎么能这样做?
答案 0 :(得分:0)
您的returnType
被宣布为AnyClass
。所以当然它没有来自Json的成员。可能你需要声明为具有此方法的类类型。