如何将字符串转换为字典数组的数组?

时间:2017-07-23 21:13:07

标签: swift

我已成功将字典数组转换为字符串,但将其转换回来证明非常具有挑战性。建议?

1 个答案:

答案 0 :(得分:4)

[[String: Any]]不是"字典数组"。它是一系列字典。这是JSON的一个例子:

func toJSON(array: [[String: Any]]) throws -> String {
    let data = try JSONSerialization.data(withJSONObject: array, options: [])
    return String(data: data, encoding: .utf8)!
}

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"])
    }
    return jsonObject.map { $0 as! [String: Any] }
}

测试:

let array: [[String: Any]] = [
    [
        "firstName": "John",
        "lastName": "Smith"
    ],
    [
        "make": "Ford",
        "model": "Focus",
        "year": 2016
    ]
]

let str = try! toJSON(array: array)
let array2 = try! fromJSON(string: str)

print(array2)

JSON的关键是你必须一次解码一个级别。