【发布时间】:2020-01-13 01:26:30
【问题描述】:
我在某个键中收到类似这样的响应,例如:
"abc" : "[{\"ischeck\":true,\"type\":\"Some type\"},{\"ischeck\":false,\"type\":\"other type\"}]"]"
我需要把它转换成普通数组。我正在为此使用以下功能。
[{"ischeck": true, "type":"Some type"},{"ischeck": true, "type":"other type"}]
func fromJSON(string: String) throws -> [[String: Any]] {
let data = string.data(using: .utf8)!
guard let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [AnyObject] else {
throw NSError(domain: NSCocoaErrorDomain, code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid JSON"])
}
//swiftlint:disable:next force_cast
return jsonObject.map { $0 as! [String: Any] }
}
【问题讨论】:
-
@JoakimDanielson 键
abc的值是另一个 JSON 字符串,而不是数组