【问题标题】:How to access data in nested JSON in swift如何快速访问嵌套 JSON 中的数据
【发布时间】:2016-08-15 13:21:36
【问题描述】:

我有一个json file

我需要获取最新的 "id": "article" "createdAt": "2016-04-22T03:38:39.130Z" 日期。如何快速从请求中获取这些数据?

注意:对不起,我是一个快速的新手。

【问题讨论】:

  • 应该试试 SwiftyJSON

标签: ios arrays json swift swift2


【解决方案1】:
let url = "https://cdn.contentful.com/spaces/maz0qqmvcx21/entries?access_token=ae8163cb8390af28cd3d7e28aba405bac8284f9fe4375a605782170aef2b0b48";
var jsonData:NSData?

do{
    jsonData = try NSData(contentsOfURL: NSURL(string: url)!, options: NSDataReadingOptions.DataReadingUncached)
    let jsonObject:AnyObject? = try NSJSONSerialization.JSONObjectWithData(jsonData!, options: NSJSONReadingOptions.AllowFragments)
    if let itemArray = jsonObject?.objectForKey("items") as? NSArray{
        for item in itemArray{
            if let sysItem = item.objectForKey("sys"){
                //this is createdAt
                if let createdAt = sysItem.objectForKey("createdAt") as? String{
                    print("createdAt:\(createdAt)")
                }

                if let contentTypeItem = sysItem.objectForKey("contentType")!.objectForKey("sys"){
                    //this is id
                    if let id = contentTypeItem.objectForKey("id") as? String{
                        print("id:\(id)")
                    }
                }
            }
        }
    }
}catch let err as NSError{
    print("err:\(err)")
}

这段代码不使用任何库,但是你可以使用SwiftyJSON,这样解析json会很容易。

希望对您有所帮助。

【讨论】:

  • 谢谢!解决了我的问题:)。
【解决方案2】:

这可以通过简单的方式完成。我假设您已将 json 解析为字典

您有一个带有 items 的键,它是一个字典数组,并且在该字典中您创建了 At 和 id(它在层次结构中更深,但我将向您展示如何获取它)键。您只需执行此操作即可访问它。

for dict in jsonDict["items"] as! Array<NSDictionary> {
    let sysDict = dict["sys"] as! NSDictionary
    print(sysDict["createdAt"]) //prints all createdAt in the array
    let contentDict = sysDict["contentType"]
    print((contentDict["sys"] as! NSDictionary)["id"]) // prints all ids
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多