Swift JSONSerialization implicitly convert double value to string

Viewed 1172

I want convert a json string which contains a double field to JSON object using JSONSerialization.data function. I print the result json object and it shows the double field as string. The following is the sample code:

let test = "{\"statusCode\":2.334}"

do {
    let responseJSON = try JSONSerialization.jsonObject(with: test.data(using: String.Encoding.utf16)!, options: [])
    print(responseJSON)
} catch {
   print(error)
}

The responseJSON as following:

{
    statusCode = "2.334";
}

I have two questions:

  1. Is it, in general, all JSON serialization engine will convert double value to string or it is only happen in Swift JSON serialization?

  2. Anyway to force JSONSerialization to output double, not string?

1 Answers

This is purely an artifact of how the value is printed out — the value you get is in fact a Double. You can confirm this yourself with the following:

import Foundation

let test = "{\"statusCode\":2.334}"

do {
    let responseJSON = try JSONSerialization.jsonObject(with: test.data(using: String.Encoding.utf16)!, options: []) as! [String: Any]
    print(responseJSON["statusCode"] is Double) // => true
} catch {
   print(error)
}
Related