繁体   English   中英

迅速将JSON字符串数组转换为NSArray

[英]Convert JSON string array to NSArray in swift

我在某些密钥中收到类似这样的响应:

"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] }
}

您必须两次调用JSONSerialization.jsonObject 首先反序列化根对象,然后反序列化密钥abc的JSON字符串。

func fromJSON(string: String) throws -> [[String: Any]] {
    let data = Data(string.utf8)
    guard let rootObject = try JSONSerialization.jsonObject(with: data) as? [String:String],
        let innerJSON = rootObject["abc"]  else {
            throw NSError(domain: NSCocoaErrorDomain, code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid JSON"])
    }
    let innerData = Data(innerJSON.utf8)
    guard let innerObject = try JSONSerialization.jsonObject(with: innerData) as? [[String:Any]] else {
        throw NSError(domain: NSCocoaErrorDomain, code: 1, userInfo: [NSLocalizedDescriptionKey: "Invalid JSON"])
    }
    return innerObject
}

另一个更舒适的方法是使用Decodable解码字符串

let jsonString = """
{"abc":"[{\\"ischeck\\":true,\\"type\\":\\"Some type\\"},{\\"ischeck\\":false,\\"type\\":\\"other type\\"}]"}
"""

struct Root : Decodable {
    let abc : [Item]

    private enum CodingKeys : String, CodingKey { case abc }

    init(from decoder : Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        let abcString = try container.decode(String.self, forKey: .abc)
        abc = try JSONDecoder().decode([Item].self, from: Data(abcString.utf8))
    }
}

struct Item : Decodable {
    let ischeck : Bool
    let type : String
}

do {
   let result = try JSONDecoder().decode(Root.self, from: Data(jsonString.utf8))
   print(result.abc) 
} catch {
    print(error)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM