简体   繁体   English

Swift JSONSerialization 将双精度值隐式转换为字符串

[英]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.我想使用 JSONSerialization.data 函数将包含双字段的 json 字符串转换为 JSON 对象。 I print the result json object and it shows the double field as string.我打印结果 json 对象,它将双字段显示为字符串。 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: responseJSON 如下:

{
    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?一般来说,所有 JSON 序列化引擎都会将 double 值转换为字符串,还是只发生在 Swift JSON 序列化中?

  2. Anyway to force JSONSerialization to output double, not string?无论如何要强制 JSONSerialization 输出双精度,而不是字符串?

This is purely an artifact of how the value is printed out — the value you get is in fact a Double .这纯粹是值如何打印出来的人工制品——你得到的值实际上是一个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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM