如何从swift中的嵌套字典中获取json数据

时间:2016-07-21 09:37:51

标签: ios json swift

如何从嵌套字典中访问数据 - 当我想保存来自" CourseDates的所有数据时? CourseDates = NSArrayM

json

let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments)

if let test = json[0]["CourseDates"] as? [[String : AnyObject]] {
// heres my problem
 }

3 个答案:

答案 0 :(得分:3)

您可以创建一个返回NSDictionary的函数,如下所示:

func parseJSON(data: NSData) -> NSDictionary{
        var dic: NSDictionary!
        do {
            boardsDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

        } catch let error as NSError {
            print(error.localizedDescription)
            print("Error could not parse JSON data, it's null maybe?!!")
        }
        //'\(jsonStr)'

        return dic
    }

更新:

添加此内容:

public class func jsonToNSData(json: AnyObject) -> NSData?{
    return NSJSONSerialization.dataWithJSONObject(json, options: .allZeros, error: nil)
}

let dic = parseJSON(jsonToNSData(YourJsonData)) as! NSDictionary

答案 1 :(得分:1)

您好,您可以尝试SwiftyJson,这是一个很好的来源,通过它您可以以一种比您想象的更简单的方式处理复杂的JSON。例如 { "metadata":{ "responseInfo":{ "status":200, "developerMessage":"OK", } }, "results":[ { "title":"Legal immigrants should get freedom before undocumented immigrants – moral, just and fair", "body":"I am petitioning President Obama's Administration to take a humane view of the plight of legal immigrants. Specifically, legal immigrants in Employment Based (EB) category. I believe, such immigrants were short changed in the recently announced reforms via Executive Action (EA), which was otherwise long due and a welcome announcement.", "issues":[ { "id":"28", "name":"Human Rights" }, { "id":"29", "name":"Immigration" } ], "signatureThreshold":100000, "signatureCount":267, "signaturesNeeded":99733, }, { "title":"National database for police shootings.", "body":"There is no reliable national data on how many people are shot by police officers each year. In signing this petition, I am urging the President to bring an end to this absence of visibility by creating a federally controlled, publicly accessible database of officer-involved shootings.", "issues":[ { "id":"28", "name":"Human Rights" } ], "signatureThreshold":100000, "signatureCount":17453, "signaturesNeeded":82547, } ] }

如果您想要提取结果,可以从这个JSON中轻松完成这个

func parseJSON(json: JSON) {
for result in json["results"].arrayValue {
    let title = result["title"].stringValue
    let body = result["body"].stringValue
    let sigs = result["signatureCount"].stringValue
    let obj = ["title": title, "body": body, "sigs": sigs]
    objects.append(obj)
}

}

答案 2 :(得分:1)

这是一个简单的例子,我们如何从NSDictionary中提取数据。这很简单,我没有遵循任何标准......

我用String格式考虑 json数据。

var data = "{\"data\":{\"fName\":\"naveen\",\"lName\":\"kumar\"},\"friend\":[{\"name\":\"manju\",\"male\":true},{\"name\":\"tanuja\",\"male\":false}]}"

之后你可以做

var nsdata = data.dataUsingEncoding(NSUTF16StringEncoding)
if let json = try? NSJSONSerialization.JSONObjectWithData(nsdata!, options: .MutableContainers) as! NSDictionary {         
    if let some = json["friend"]![0]["name"]! {
        print(some) // prints -- manju
    }
}

通过使用subscipt,我们可以获得数据。