首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为稍微不同的json响应创建可编码的公共代码- Swift

问为稍微不同的json响应创建可编码的公共代码- Swift
EN

Stack Overflow用户
提问于 2022-02-12 03:54:56
回答 1查看 49关注 0票数 1

如何为稍微不同的json示例创建一个通用的可编码结构,responses.For示例response A和B具有几乎相同的属性,而B有一些额外的属性,称为Designation.Is,可以为此场景创建通用可编码结构吗?

代码语言:javascript
复制
//Response A
{
  "name" : "Jhon",
  "age" : 23,
  "mobile" : "+11012341234",
  .
  .
  .
}

//Response B
{
  "name" : "Jhon",
  "age" : 23,
  "mobile" : "+11012341234",
  .
  .
  .
  "designation": "Manager"
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-12 03:58:34

您可以使用这样的选项:

代码语言:javascript
复制
struct Response: Decodable {

   var name: String
   var age: Int
   var mobile: String
   var designation: String?

   // If you need to decode, it would look like this:
   init(from decoder: Decoder) throws {

      let container = try decoder.container(keyedBy: CodingKeys.self)

      name = try container.decode(String.self, forKey: .name)
      age = try container.decode(Int.self, forKey: .age)
      mobile = try container.decode(String.self, forKey: .mobile)

      // Decode designation if provided
      if container.contains(.designation){
         designation = try container.decode(String.self, forKey: .designation)
      }
   }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71088877

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档