我创建了一个自定义协议,我打算用它代替Any
但是当我尝试从JSONSerialization.jsonObject
这是我的自定义协议
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)
}
但是,如果我尝试将其转换为2个步骤,则其工作原理如下
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",
}
我不明白为什么第一段代码不起作用而第二段代码却起作用......
由于
答案 0 :(得分:1)
它不是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)
}
}
在Apple上打印
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 :-)并更改代码,使其工作方式有效在我的游乐场没有任何警告和错误,并... 打印预期结果:)
为什么现在有效?关键是
/* 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上的这个片段:-)和苹果。
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)
}
}
apple print
[1.0, 1e+20]
而linux
[]
并且具有非常大的价值会崩溃。这个bug来自(在开源的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)
}
}
和'反序列化'按预期工作(序列化还有其他错误......)
答案 1 :(得分:0)
使用is
代替as
if json is [String : StringOrNumber] {
print("valid")
}
else {
print("invalid")
}
if let object = (json as? [String: Any]) as? [String : StringOrNumber] {
print("valid object = \(object)")
}
else {
print("invalid")
}