I have a request that implicitly converts to Int from Double. I need the format of my paramaters unchanged. For example below, I am sending amount of 300.0, when I print out the request It sends as Int 300 instead of a Double.
let params = [
"id": "xxx",
"amount": 300.0
] as [String : Any]
let jsonData = try? JSONSerialization.data(withJSONObject: params)
let url = URL(string: "BASE_URL")
var request = URLRequest(url: url!)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = jsonData
When I print the request, this is what I get:
{"id":"xxx", "amount":300}
Instead of {"id":"xxx", "amount":300.0}
That's not how JSON works. JSON draws no inherent distinction between numeric types. So the JSON you are seeing is the equivalent of the data you put into it, because there is no distinction between 300
and 300.0
. (If you had put in 300.1
, of course, you would see something more like 300.1
.)
If a client wants to treat your number as a Double, that is up to the client. But you cannot put a Double in. All you can put in is a Number.