如何根据接收参数的类型来解码JSON字符串?

发布于 2025-02-06 11:08:43 字数 1128 浏览 2 评论 0原文

我有这个代码段(专门为这个问题设计):

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文