Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift JSONSerialization implicitly convert double value to string

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?

like image 588
Cyrus Avatar asked Apr 27 '26 05:04

Cyrus


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)
}
like image 69
Itai Ferber Avatar answered Apr 30 '26 07:04

Itai Ferber