我想使用JSONSerialization.data函数将包含双精度字段的json字符串转换为JSON对象。我打印结果json对象,它将双精度字段显示为字符串。以下是示例代码:
let test = "{\"statusCode\":2.334}"
do {
let responseJSON = try JSONSerialization.jsonObject(with: test.data(using: String.Encoding.utf16)!, options: [])
print(responseJSON)
} catch {
print(error)
}
responseJSON如下:
{
statusCode = "2.334";
}
我有两个问题:
是一般情况下,所有JSON序列化引擎都将double值转换为字符串,还是仅在Swift JSON序列化中发生?
无论如何要强制JSONSerialization输出双精度,而不是字符串?
这纯粹是关于如何打印出值的伪像-您获得的值实际上是a Double
。您可以使用以下方法自行确认:
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)
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句