使用Swift读取JSON文件

前端之家收集整理的这篇文章主要介绍了使用Swift读取JSON文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我真的很努力尝试读一个JSON文件到Swift,所以我可以玩弄它。我花了2天的最好的一部分重新搜索和尝试不同的方法,但没有运气,因此我已经注册了StackOverFlow,看看是否有人可以指向我的方向正确…..

我的JSON文件称为test.json,包含以下内容

{
  "person":[
     {
       "name": "Bob","age": "16","employed": "No"
     },{
       "name": "Vinny","age": "56","employed": "Yes"
     }
  ]
}

文件直接存储在文档中,我使用以下代码访问它:

let file = "test.json"
let dirs : String[] = NSSearchPathForDirectoriesInDomains(
                                                          NSSearchpathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainMask,true) as String[]

if (dirs != nil) {
    let directories: String[] = dirs
    let dir = directories[0]
    let path = dir.stringByAppendingPathComponent(file)
}

var jsonData = NSData(contentsOfFile:path,options: nil,error: nil)
println("jsonData \(jsonData)" // This prints what looks to be JSON encoded data.

var jsonDict = NSJSONSerialization.JSONObjectWithData(jsonData,error: nil) as? NSDictionary

println("jsonDict \(jsonDict)") - This prints nil.....

如果任何人只能给我一个正确的方向推我如何解序列化的JSON文件,并把它放在一个可访问的Swift对象,我会永远感激!

亲切的问候,

Krivvenz。

按照下面的代码
if let path = NSBundle.mainBundle().pathForResource("test",ofType: "json")
{
    if let jsonData = NSData(contentsOfFile: path,options: .DataReadingMappedIfSafe,error: nil)
    {
        if let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData,options: NSJSONReadingOptions.MutableContainers,error: nil) as? NSDictionary
        {
            if let persons : NSArray = jsonResult["person"] as? NSArray
            {
                // Do stuff
            }
        }
     }
}

数组“persons”将包含关键人物的所有数据。迭代通过获取它。

原文链接:https://www.f2er.com/swift/321372.html

猜你在找的Swift相关文章