how to pase JSON in Swift

来源:互联网 发布:商业数据分析 编辑:程序博客网 时间:2024/06/04 06:16

http://roadfiresoftware.com/2015/10/how-to-parse-json-with-swift-2/

Example:
{
“blogs”: [
{
“needspassword”: true,
“id”: 73,
“url”: “http://remote.bloxus.com/“,
“name”: “Bloxus test”
},
{
“needspassword”: false,
“id”: 74,
“url”: “http://flickrtest1.userland.com/“,
“name”: “Manila Test”
}
],
“stat”: “ok”
}

var names = String

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

if let blogs = json["blogs"] as? [[String: AnyObject]] {    for blog in blogs {        if let name = blog["name"] as? String {            names.append(name)        }    }}

} catch {
print(“error serializing JSON: (error)”)
}

print(names) // [“Bloxus test”, “Manila Test”]

if let blogs = json[“blogs”] as? [[String: AnyObject]] {
// if we get “blogs” from the JSON
// AND we can cast it to an array of dictionaries
// then this code will execute
}

for blog in blogs {
if let name = blog[“name”] as? String {
names.append(name)
}
}

0 0