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:
Is it, in general, all JSON serialization engine will convert double value to string or it is only happen in Swift JSON serialization?
Anyway to force JSONSerialization to output double, not string?
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With