如何在Swift中将JSON字符串转换为Object?

时间:2015-03-29 11:35:41

标签: json swift object

你好我是Swift的新手,我有这个链接http://api.sabriapps.com/FikraSpace/db.json,我想将这个JSON转换为Swift中的对象&还有另一个问题,即加载图片非常慢

2 个答案:

答案 0 :(得分:0)

您可以在目标c:

中使用NSJSONSerialization类

https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/index.html#//apple_ref/occ/clm/NSJSONSerialization/JSONObjectWithData:options:error

JSONObjectWithData方法返回一个你可以解析的NSDictionary或NSArray

答案 1 :(得分:0)

以下是您需要的代码:

 let data = NSData(contentsOfURL:NSURL(string: "http://api.sabriapps.com/FikraSpace/db.json")!, options: nil, error: nil)

    var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!,options: NSJSONReadingOptions.MutableContainers,
        error: nil) as NSDictionary

    println("Dictionary :  \(jsonResult)")

    var jsonEvents = jsonResult["events"] as NSArray

    println("Array :  \(jsonEvents)")

    var firstObject : NSDictionary = jsonEvents[0] as NSDictionary ;

    println("First Obj :  \(firstObject)")

    var name = firstObject["name"] as NSString

    println("Name :  \(name)")

    var timeStamp = firstObject["timestamp"] as NSString

    println("TimeStamp :  \(timeStamp)")

    var duration = firstObject["name"] as NSString

    println("duration :  \(duration)")

    var description_en = firstObject["description_en"] as NSString

    println("Description :  \(description_en)")

    var location = firstObject["location"] as NSString

    println("Location :  \(location)")