Flight-School / AnyCodable

Type-erased wrappers for Encodable, Decodable, and Codable values
https://flight.school/books/codable
MIT License
1.28k stars 132 forks source link

Int variable having 0 or 1 in JSON is getting converted into Bool by this library #16

Closed neerajkhede16 closed 5 years ago

neerajkhede16 commented 5 years ago

Please see sample code and its output:

    let encoder = JSONEncoder()
    let sample = People(name: "neeraj", age: 1)
    let data = try! encoder.encode(sample)
    let dictionary = try! JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
    let str1 = String.init(data: data, encoding: .utf8)
    print(str1!)  // print: {"name":"neeraj","age":1}

    let d1 = ["data":AnyCodable(dictionary)]
    let data1 = try! encoder.encode(d1)
    let str2 = String.init(data: data1, encoding: .utf8)
    print(str2!)  // print: {"data":{"name":"neeraj","age":true}}

struct People:Codable{ var name:String? var age:Int? }

{"name":"qwertyui","age":1} {"data":{"name":"qwertyui","age":true}}

We can see age value (1) is converted into bool value (true).

mattt commented 5 years ago

The reason for this behavior is that JSONSerialization produces an NSNumber value for the key "age". An NSNumber value of 1 can be bridged to a Bool, which is the first type checked in encode(to:). See Table 1 in Apple's documentation for NSNumber.

I believe I've fixed this with f443ddc. Can you please confirm whether this solves your problem?

neerajkhede16 commented 5 years ago

Yes, this is fixed now. Many thanks for your quick fix.