首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Swift读取JSON文件

使用Swift读取JSON文件
EN

Stack Overflow用户
提问于 2014-06-25 22:04:26
回答 19查看 283.8K关注 0票数 257

我真的很难尝试将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, options: nil, error: nil) as? NSDictionary

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

如果有人能给我一个正确的方向,告诉我如何反序列化JSON文件并将其放在一个可访问的Swift对象中,我将永远感激不尽!

致以亲切的问候,

克里夫文兹。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24410881

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档