gpt4 book ai didi

在 Swift 3 中使用可选项的 JSONSerialization

转载 作者:搜寻专家 更新时间:2023-10-31 08:17:54 24 4
gpt4 key购买 nike

在 Swift 3 中,具有可选值的数组的 JSONSerialization 失败。
这在 Swift 2 中有效(产生 null 作为 nil 的 JSON 值正如预期的那样是可选的)。

编辑:它没有,但把它留在这里,因为这是我问问题时的错误信念。

swift 2:

let a: [String!] = ["a","b","c"]
let b: [String] = ["a","b","c"]

let s: String! = "a"
let c = ["a",s]

NSJSONSerialization.isValidJSONObject(a) //true
NSJSONSerialization.isValidJSONObject(b) //true
NSJSONSerialization.isValidJSONObject(c) //true

swift 3:

let a: [String?] = ["a","b","c"]
let b: [String] = ["a","b","c"]

let s: String! = "a"
let c = ["a",s]

JSONSerialization.isValidJSONObject(a) //false
JSONSerialization.isValidJSONObject(b) //true
JSONSerialization.isValidJSONObject(c) //false

这是有意更改吗?
这似乎很容易出错,因为使用隐式类型构造的任何数组或字典现在可能对 JSON 无效(即使它们实际上不包含任何 nil 值)。

此外,如何指定空值?

最佳答案

更新:从 Swift 3.0.1/Xcode 8.1 beta 2 开始, optionals自动桥接到 NSNull 实例,请参阅

和 Xcode 8.1 beta 发行说明。

例子:

let array: [String?] = [ "a", nil, "c"]
let jsonData = try! JSONSerialization.data(withJSONObject: array)

print(String(data: jsonData, encoding: .utf8)!)
// ["a",null,"c"]

Swift 2 和 3.0 的先前答案:只有 NSNull() 被序列化为 JSON null,而不是可选项(独立于 Swift 版本)。

一个可选数组可以这样转换:

let a: [String?] = ["a", nil, "c"]

let b = a.map { $0 as Any? ?? NSNull() }
print(b) // ["a", <null>, "c"]

let d = try! JSONSerialization.data(withJSONObject: b)
print(String(data: d, encoding: .utf8)!) // ["a",null,"c"]

关于在 Swift 3 中使用可选项的 JSONSerialization,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39975778/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com