利用 swift 自带 JSON 功能在对象和 JSON 间相互转换

参考链接: 在swift 中使用 JSON.

在 Swift 中提供了 JSON 转换的功能, 使用起来很方便, 下面来看如何将一个对象转换为 JSON, 或者是将一个 JSON 转换为对象. 主要利用的是 Foundation framework 中的 JSONSerialization 类实现转换.

1 对象转换为 JSON

    public func toJSONString() -> String {
        do {
            let dict = toDictionary()
            let jsonData = try JSONSerialization.data(withJSONObject: dict, options: [])
            let jsonString = String.init(data: jsonData, encoding: .utf8) ?? ""
            return jsonString
        } catch {
            print(error)
            return ""
        }
    }

  func toDictionary() -> [String: Any] {
        var dictionary = [String: Any]()
        let otherSelf = Mirror(reflecting: self)
        for child in otherSelf.children {
            guard let key = child.label else { continue }
            dictionary[key] = child.value
        }
        return dictionary
    }

2 JSON 数据转换为对象

首先是在网络上获取到 JSON 数据, 并进行转换:

let data: Data // received from a network request, for example
let json = try? JSONSerialization.jsonObject(with: data, options: [])

上面的代码将 JSON 数据转换为 JSON 字典. 由于 JSON 顶层或是数组, 或是对象, 这里就需要针对不同的数据来转换为不同的内容, 但转换都是通过 as? 来完成:

let jsonObj = json as? [类型]    // 数据顶层是数组的情况
// 或者
let jsonObj = json as? [String: Any]  // 数据顶层是 JSON 对象的情况

得到数组的话, 就针对每一个元素转换为 swift 对象, 得到对象的话, 就按需转换即可.

你可能感兴趣的:(利用 swift 自带 JSON 功能在对象和 JSON 间相互转换)