我有一个字典数组,想将其转换为JSON格式。我的对象类型为[[String: AnyObject]]
,希望最终得到类似于以下示例的结果:
[
{ "abc": 123, "def": "ggg", "xyz": true },
{ "abc": 456, "def": "hhh", "xyz": false },
{ "abc": 789, "def": "jjj", "xyz": true }
]
这就是我尝试的,但编译器不喜欢我的声明:
extension Array where Element == Dictionary<String, AnyObject> {
var json: String {
do { return try? NSJSONSerialization.dataWithJSONObject(self, options: []) ?? "[]" }
catch { return "[]" }
}
}
我该如何做到这一点?
dataWithJSONObject
在成功时返回NSData
,因此至少需要创建一个字符串来返回。 - vadian