我有一系列字典,我想转换为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 "[]" }
}
}
我该怎么做?
答案 0 :(得分:7)
实现这一目标的一种简单方法是扩展CollectionType。
使用可选的绑定和向下转换,然后序列化为数据,然后转换为字符串。
extension CollectionType where Generator.Element == [String:AnyObject] {
func toJSONString(options: NSJSONWritingOptions = .PrettyPrinted) -> String {
if let arr = self as? [[String:AnyObject]],
let dat = try? NSJSONSerialization.dataWithJSONObject(arr, options: options),
let str = String(data: dat, encoding: NSUTF8StringEncoding) {
return str
}
return "[]"
}
}
let arrayOfDictionaries: [[String:AnyObject]] = [
["abc":123, "def": "ggg", "xyz": true],
["abc":456, "def": "hhh", "xyz": false]
]
print(arrayOfDictionaries.toJSONString())
输出:
[
{
"abc" : 123,
"def" : "ggg",
"xyz" : true
},
{
"abc" : 456,
"def" : "hhh",
"xyz" : false
}
]
答案 1 :(得分:3)
Swift 4 :
extension Collection where Iterator.Element == [String:AnyObject] {
func toJSONString(options: JSONSerialization.WritingOptions = .prettyPrinted) -> String {
if let arr = self as? [[String:AnyObject]],
let dat = try? JSONSerialization.data(withJSONObject: arr, options: options),
let str = String(data: dat, encoding: String.Encoding.utf8) {
return str
}
return "[]"
}
}
<强>用法:强>
let arrayOfDictionaries = [
{ "abc": 123, "def": "ggg", "xyz": true },
{ "abc": 456, "def": "hhh", "xyz": false },
{ "abc": 789, "def": "jjj", "xyz": true }
]
print(arrayOfDictionaries.toJSONString())
答案 2 :(得分:0)
我认为您在尝试扩展Array
时运气不佳,因为在扩展实体时无法实现相同类型的要求。
你可以做的是利用免费功能:
func jsonify(array: [[String:AnyObject]]) {
...
}
通过这种方式,您可以保持所需的类型安全,但需要花费移动功能位置。
答案 3 :(得分:0)
Swift 5,我不得不将其更改为 Any
而不是 AnyObject
,构建了 Eric & A.G. 的解决方案
extension Collection where Iterator.Element == [String: Any] {
func toJSONString(options: JSONSerialization.WritingOptions = .prettyPrinted) -> String {
if let arr = self as? [[String: Any]],
let dat = try? JSONSerialization.data(withJSONObject: arr, options: options),
let str = String(data: dat, encoding: String.Encoding.utf8) {
return str
}
return "[]"
}
}
用法:
let arrayOfDictionaries = [
{ "abc": 123, "def": "ggg", "xyz": true },
{ "abc": 456, "def": "hhh", "xyz": false },
{ "abc": 789, "def": "jjj", "xyz": true }
]
print(arrayOfDictionaries.toJSONString())