【问题标题】:How to convert JSON string to Object in Swift? [closed]如何在 Swift 中将 JSON 字符串转换为对象? [关闭]
【发布时间】:2015-03-29 11:35:40
【问题描述】:

您好,我是 Swift 的新手,我有这个链接 http://api.sabriapps.com/FikraSpace/db.json,我想在 Swift 中将此 JSON 转换为 Objects 并且还有另一个问题是加载图片非常慢

【问题讨论】:

标签: json swift object


【解决方案1】:

这是您需要的代码:

 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)")

【讨论】:

  • 非常感谢,但是如何在collectionview单元格上显示呢?
  • 通过:youtube.com/watch?v=9STtYpxIwj4。如果对您有帮助,请接受我的回答。
  • 伙计,OP 对他的问题没有任何努力。他说“我如何快速解析这个 JSON”,然后你给他写了一堆代码。不要那样做。这不是一个“为我写代码”的网站。在付出努力之后,它是一个帮助解决您编写的代码问题的网站。你的回答很全面,但给了 OP 太多了。 OP 现在可以复制/粘贴您的代码,而不会学到任何东西。
  • 请注意他对另一个答案的评论:“你能帮我输入代码吗?”翻译:“你能帮我完成我所有的工作,以便我可以复制/粘贴它。”
【解决方案2】:

您可以像在目标 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,然后您可以对其进行解析

【讨论】:

  • 你能帮我输入代码吗?
猜你喜欢
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-30
  • 2018-01-06
相关资源
最近更新 更多