加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

使用Swift读取JSON文件

发布时间:2020-12-14 06:10:35 所属栏目:百科 来源:网络整理
导读:我真的很努力尝试读一个JSON文件到Swift,所以我可以玩弄它。我花了2天的最好的一部分重新搜索和尝试不同的方法,但没有运气,因此我已经注册了StackOverFlow,看看是否有人可以指向我的方向正确….. 我的JSON文件称为test.json,包含以下内容: { "person":
我真的很努力尝试读一个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”将包含关键人物的所有数据。迭代通过获取它。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读