在没有密钥的情况下解析JSON?

时间:2016-06-12 16:04:39

标签: ios json swift parsing

如何在方括号前没有键解析此数组?

[
    {
        "id": 2,
        "model": "RAV 4",
        "brand": "Toyota"
    },
    {
        "id": 1,
        "model": "A6",
        "brand": "Audi"
    }
]

similar question,但适用于Android。

2 个答案:

答案 0 :(得分:2)

正常使用NSJSONSerialization解析它,并将结果转换为[String:AnyObject]词典数组。

所以,比如:

if let json = (try? NSJSONSerialization.JSONObjectWithData(yourLoadedNSData, options: NSJSONReadingOptions(rawValue: 0))) as? [[String : AnyObject]] {
    print(json.count) // Should be 2, based on your sample json above
}

答案 1 :(得分:0)

Swift 3的更新

if let json = (try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions(rawValue: 0))) as? [String] {
// do stuff here
}

以防万一:)