我有需要转换为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
的情况?
答案 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
,我会再考虑一下。