我已经创建了一个自定义协议(protocol),我打算用它来代替 Any
但是当我尝试从 JSONSerialization.jsonObject
这是我的自定义协议(protocol)
public protocol StringOrNumber {}
extension String:StringOrNumber {}
extension NSNumber:StringOrNumber {}
extension Bool:StringOrNumber {}
extension Float:StringOrNumber {}
extension CGFloat:StringOrNumber {}
extension Int32:StringOrNumber {}
extension Int64:StringOrNumber {}
extension Int:StringOrNumber {}
extension Double:StringOrNumber {}
extension Dictionary:StringOrNumber {}
extension Array:StringOrNumber {}
extension NSDictionary:StringOrNumber {}
extension NSArray:StringOrNumber {}
extension NSString:StringOrNumber {}
extension NSNull:StringOrNumber {}
这是我希望工作但没有的代码
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let object = json as? [String: StringOrNumber] {
// json is a dictionary
print(object)
}
但是,如果我尝试分两步转换它,它的工作原理如下
let json = try JSONSerialization.jsonObject(with: data, options: [])
if let object = json as? [String: Any] {
// json is a dictionary
print(object)
if let newObject:[String:StringOrNumber] = object as? [String:StringOrNumber] {
// json is a newer dictionary
print(newObject)
}
}
这是我从文件中读取的示例 JSON。(没关系,您也可以自己尝试)
{
"firstName": "John",
}
我不明白为什么第一段代码行不通而第二段代码行...
谢谢
最佳答案
它不是 Swift(语言)特定的,它是 Apple 特定的......
如果您将数据更改为
let d = ["first":"john", "last":"doe", "test int": 0, "test null": NSNull()] as [String:Any]
linux 版本按预期工作,
["test null": <NSNull: 0x0000000000825560>, "last": "doe", "first": "john", "test int": 0]
["test null": <NSNull: 0x0000000000825560>, "last": "doe", "first": "john", "test int": 0]
["test int": 0, "last": "doe", "first": "john", "test null": <NSNull: 0x0000000000825560>]
但是苹果打印
[:]
[:]
{
first = john;
last = doe;
"test int" = 0;
"test null" = "<null>";
}
看起来很奇怪。下一个代码片段解释原因
import Foundation
public protocol P {}
extension String:P {}
extension Int:P {}
extension NSNull:P {}
let d = ["first":"john", "last":"doe", "test null": NSNull(), "test int": 10] as [String:Any]
print("A)",d, type(of: d))
let d1 = d as? [String:P] ?? [:]
print("B)",d1, type(of: d1))
print()
if let data = try? JSONSerialization.data(withJSONObject: d, options: []) {
if let jobject = try? JSONSerialization.jsonObject(with: data, options: []) {
let o = jobject as? [String:Any] ?? [:]
print("1)",o, type(of: o))
var o2 = o as? [String:P] ?? [:]
print("2)",o2, type(of: o2), "is it empty?: \(o2.isEmpty)")
print()
if o2.isEmpty {
o.forEach({ (t) in
let v = t.value as? P
print("-",t.value, type(of: t.value),"as? P", v as Any)
o2[t.key] = t.value as? P ?? 0
})
}
print()
print("3)",o2)
}
}
它在苹果上打印
A) ["test null": <null>, "test int": 10, "first": "john", "last": "doe"] Dictionary<String, Any>
B) ["test null": <null>, "test int": 10, "first": "john", "last": "doe"] Dictionary<String, P>
1) ["test null": <null>, "test int": 10, "first": john, "last": doe] Dictionary<String, Any>
2) [:] Dictionary<String, P> is it empty?: true
- <null> NSNull as? P Optional(<null>)
- 10 __NSCFNumber as? P nil
- john NSTaggedPointerString as? P nil
- doe NSTaggedPointerString as? P nil
3) ["test null": <null>, "test int": 0, "first": 0, "last": 0]
在 linux 上打印
A) ["test int": 10, "last": "doe", "first": "john", "test null": <NSNull: 0x00000000019d8c40>] Dictionary<String, Any>
B) ["test int": 10, "last": "doe", "first": "john", "test null": <NSNull: 0x00000000019d8c40>] Dictionary<String, P>
1) ["test int": 10, "last": "doe", "first": "john", "test null": <NSNull: 0x00000000019ec550>] Dictionary<String, Any>
2) ["test int": 10, "last": "doe", "first": "john", "test null": <NSNull: 0x00000000019ec550>] Dictionary<String, P> is it empty?: false
3) ["test int": 10, "last": "doe", "first": "john", "test null": <NSNull: 0x00000000019ec550>]
最后,我使用了来自开源发行版的稍微修改过的 JSONSerialization 源代码(为了避免与 apple Foundation 发生冲突,我将类重命名为 _JSONSerialization :-) 并按照它的工作方式更改代码在我的 Playground 上没有任何警告和错误...... 它打印出预期的结果:)
为什么它现在有效?关键是
/* A class for converting JSON to Foundation/Swift objects and converting Foundation/Swift objects to JSON. An object that may be converted to JSON must have the following properties:
- Top level object is a `Swift.Array` or `Swift.Dictionary`
- All objects are `Swift.String`, `Foundation.NSNumber`, `Swift.Array`, `Swift.Dictionary`, or `Foundation.NSNull`
- All dictionary keys are `Swift.String`s
- `NSNumber`s are not NaN or infinity */
现在,所有可能的值到 P 的条件向下转换按预期工作
老实说,在 linux 和 apple 上试试这个片段。
let d3 = [1.0, 1.0E+20]
if let data = try? JSONSerialization.data(withJSONObject: d3, options: []) {
if let jobject = try? JSONSerialization.jsonObject(with: data, options: []) as? [Double] ?? [] {
print(jobject)
}
}
苹果版画
[1.0, 1e+20]
在 Linux 上
[]
并且具有非常大的值(value)会崩溃。这个错误来自(在开源的 JSONSerialization 中)
if doubleResult == doubleResult.rounded() {
return (Int(doubleResult), doubleDistance)
}
替换为
if doubleResult == doubleResult.rounded() {
if doubleResult < Double(Int.max) && doubleResult > Double(Int.min) {
return (Int(doubleResult), doubleDistance)
}
}
并且“反序列化”按预期工作(序列化还有其他错误......)
关于Swift Casting 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43862710/