Reputation: 813
I have JSON data that I need to convert to Dictionary
so I use JSONSerialization
for that purpose but when I check the created dictionary, I can see that it converts the Bool
to NSNumber
(for property named demo)automatically
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)
}
OUTPUT
["meta": { demo = 1; }, "employeeID": 1]
Is there a way to avoid this Bool
to NSNumber
conversion or maybe convert NSNumber
back to Bool
using a custom logic ?
Upvotes: 0
Views: 751
Reputation: 7585
For decoding I need to convert that
Dictionary
toData
which I will input inJSONDecoder
If that is the case, you would use the data(withJSONObject:options:) method instead.
Below is how you would do that:
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)
}
And I would think again if I really need the properties of the struct
s to be Optional
s.
Upvotes: 1