避免JSONSerialization将Bool转换为NSNumber

时间:2019-12-20 05:29:53

标签: ios json swift

我有需要转换为Dictionary的JSON数据,因此我为此使用JSONSerialization,但是当我检查创建的字典时,我可以看到它将Bool转换为NSNumber(对于名为 demo 的属性)自动

import Foundation

struct Employee: Codable {
    let employeeID: Int?
    let meta: Meta?
}

struct Meta: Codable {
    let demo: Bool?
}

let jsonValue = """
{
    "employeeID": 1,
    "meta": {
        "demo": true
    }
}
"""

let jsonData = jsonValue.data(using: .utf8)!

if let jsonDictionary = (try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments)) as? [String: Any] {

    print(jsonDictionary)

}

输出

  

[“元”:{       演示= 1; },“ employeeID”:1]

是否有一种方法可以避免使用自定义逻辑将此Bool转换为NSNumber或将NSNumber转换回Bool的情况?

1 个答案:

答案 0 :(得分:1)

  

要进行解码,我需要将Dictionary转换为Data,然后将其输入JSONDecoder

在这种情况下,您应该使用data(withJSONObject:options:)方法。

以下是您的操作方法:

let dictionary: [String : Any] = [ "employeeID": 1,
                                   "meta": [ "demo": true ] ]
do {
    let data = try JSONSerialization.data(withJSONObject: dictionary, options: [])
    let employee = try JSONDecoder().decode(Employee.self, from: data)
    print(employee)
} catch {
    print(error)
}

如果我真的需要将struct的属性设为Optional,我会再考虑一下。