user121095
user121095

Reputation: 813

Avoid JSONSerialization to convert Bool to NSNumber

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

Answers (1)

nayem
nayem

Reputation: 7585

For decoding I need to convert that Dictionary to Data which I will input in JSONDecoder

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 structs to be Optionals.

Upvotes: 1

Related Questions