如何根据接收参数的类型来解码JSON字符串?
我有这个代码段(专门为这个问题设计):
let data = "[{\"name\": \"Smith\", \"surname\": \"John\"}]".data(using: .utf8)!
class BaseClass: Decodable {
var name: String?
}
class ExtraClass: BaseClass {
var surname: String?
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
}
init(name: String, surname: String) {
super.init()
self.name = name
self.surname = surname
}
}
func mainFunction<T: BaseClass>(_ obj: T) {
var results = try! JSONDecoder().decode([T].self, from: data)
results.append(obj)
print(results)
}
func proxyFunction(_ obj: BaseClass) {
mainFunction(obj)
}
proxyFunction(ExtraClass(name: "Sullivan", surname: "Jane"))
我希望结果
数组将包含两个extraclass
对象,但是它包含一个BASECLASS
对象和extraclass
一个,如您所见。似乎t
是从呼叫者函数收到的类型(proxyfunction
)中推断出来的,这是一种预期,因此,jsondecoder
is将json
字符串解码。
是否有任何方法可以获取jsondeCoder
解码正确的类(不更改proxyfunction
的签名),或更确切地说,是类型obj
obj <
。 /代码>是?
I'm having this snippet of code (specially crafted for this question):
let data = "[{\"name\": \"Smith\", \"surname\": \"John\"}]".data(using: .utf8)!
class BaseClass: Decodable {
var name: String?
}
class ExtraClass: BaseClass {
var surname: String?
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
}
init(name: String, surname: String) {
super.init()
self.name = name
self.surname = surname
}
}
func mainFunction<T: BaseClass>(_ obj: T) {
var results = try! JSONDecoder().decode([T].self, from: data)
results.append(obj)
print(results)
}
func proxyFunction(_ obj: BaseClass) {
mainFunction(obj)
}
proxyFunction(ExtraClass(name: "Sullivan", surname: "Jane"))
I would expect that the results
array will contain two ExtraClass
objects, but instead it contains a BaseClass
object and a ExtraClass
one, as you may see here. Seems like T
is inferred from the type received by the caller function (proxyFunction
), which is kind of expected, and, consequently, JSONDecoder
is decoding the json
string as such.
Is there any way to get JSONDecoder
to decode the right kind of class (without altering proxyFunction
's signature) or, more precisely, the kind of class obj
is?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论