在swift中对json工作很困惑

时间:2017-06-04 18:04:13

标签: swift swift3

我在swift中使用JSON时非常困惑。 根据Apple dec:https://developer.apple.com/swift/blog/?id=37

/*
    {
        "someKey": 42.0,
        "anotherKey": {
        "someNestedKey": true
        }
    }
*/

格式化这个jsonWithObjectRoot json字符串的格式是什么? 我试过serval方式但是成功了。

因此,这些方法可以访问它。

if let dictionary = jsonWithObjectRoot as? [String: Any] {
    if let number = dictionary["someKey"] as? Double {
        // access individual value in dictionary
    }

    for (key, value) in dictionary {
        // access all key / value pairs in dictionary
    }

    if let nestedDictionary = dictionary["anotherKey"] as? [String: Any]     {
        // access nested dictionary values by key
    }
}

1 个答案:

答案 0 :(得分:0)

你的json看起来不错。你需要在转换为[String:Any]之前解析它。

let jsonWithObjectRoot = "{ \"someKey\": 42.0, \"anotherKey\": { \"someNestedKey\": true } }"
let data = jsonWithObjectRoot.data(using:.utf8)!
do {
    let json = try JSONSerialization.jsonObject(with:data)
    if let dictionary = json as? [String: Any] {
        if let number = dictionary["someKey"] as? Double {
            // access individual value in dictionary
        }

        for (key, value) in dictionary {
            // access all key / value pairs in dictionary
        }

        if let nestedDictionary = dictionary["anotherKey"] as? [String: Any]     
        { 
            // access nested dictionary values by key
        }
    }
} catch {
    print("Error parsing Json")
}