I have a Codable
object that I need to convert to Dictionary
so I first encode it to convert it to Data
and then use JSONSerialization
to convert that Data
to Any
and then use as? [String: Any]
to get the dictionary.
The conversion is successful but due to use of JSONSerialisation
, Bool
types are being converted to NSNumber
but I want to retain the Bool
value inside the Dictionary
import Foundation
struct Employee: Codable {
let employeeID: Int?
let meta: Meta?
}
struct Meta: Codable {
let demo: Bool?
}
let employeeObject = Employee(employeeID: 1, meta: Meta(demo: true))
do {
let encodedObject = try JSONEncoder().encode(employeeObject)
let dictionary = try JSONSerialization.jsonObject(with: encodedObject, options: .fragmentsAllowed) as? [String: Any]
print(dictionary ?? [:])
} catch {
print(error)
}
OUTPUT
["meta": { demo = 1; }, "employeeID": 1]
demo property is being converted to NSNumber
but I want to retain the Bool
value