[英]Swift ObjectMapper mapping an array with multiple types of values - numbers and complex objects mixed
I have this JSON object that I want to parse using Swift ObjectMapper我有这个 JSON 对象,我想使用 Swift ObjectMapper解析它
{
"id": 1,
"jsonrpc": "2.0",
"result": [
0,
{
"data": {
"username": "myuser"
},
"expires": 300,
"timeout": 300,
"ubus_rpc_session": "some_value"
}
]
}
I can't figure out how to properly parsed the inner array with mixed content, specifically this part:我不知道如何正确解析具有混合内容的内部数组,特别是这部分:
[ 0, { /* ... */ } ]
I have tried to solve it in various ways, but haven't been able to find a working solution.我试图以各种方式解决它,但一直无法找到有效的解决方案。 I suspect
StaticMappable
might work, and I have used it for other Polymorphic parsing, but never when one of the array items is a number.我怀疑
StaticMappable
可能会起作用,并且我已将它用于其他多态解析,但从未在数组项之一是数字时使用它。
Any help would be appreciated.任何帮助,将不胜感激。
I am afraid that the only way to map this array, using ObjectMapper
, is in [Any]
:恐怕使用
ObjectMapper
映射此数组的唯一方法是在[Any]
:
class Result: Mappable {
var id: Int?
var jsonrpc: String?
var result: [Any]?
required init?(map: Map) {}
func mapping(map: Map) {
id <- map["id"]
jsonrpc <- map["jsonrpc"]
result <- map["result"]
}
}
That way, for this particular json response, the first element of the array will be of type Int
and the second will be of type [String: Any]
.这样,对于这个特定的 json 响应,数组的第一个元素将是
Int
类型,第二个元素将是[String: Any]
类型。
Of course, this includes the type casting procedure whenever you are trying to access an element of this array.当然,这包括每当您尝试访问此数组的元素时的类型转换过程。 (which is just bad)
(这很糟糕)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.