ios - 如何根据key将JSON解析成不同的模型?

标签 ios swift alamofire objectmapper

例如,我需要根据来自服务器的一个特定键将 JSON 解析为不同的模型 - 如果键 =“userCoupon”,我需要将其映射到名为 UserCouponDTO 的模型中,如果键 =“discountCoupon”,我需要将响应映射到另一个名为 DiscountCouponDTO 的 DTO。我使用 Alamofire 进行网络调用,使用 ObjectMapper 进行映射。

最佳答案

在 swift 4 中,使用新的 Decodable 协议(protocol)可以很容易地将响应映射到 swift 结构

看看这篇文章:https://grokswift.com/json-swift-4/

服务器响应与结构匹配的简单示例

struct User: Decodable {
  let name: String
  let email: String?
}

在这种情况下,服务器可能会响应

{
  "name": "John"
}

let decoder = JSONDecoder()
let user = try decoder.decode(dataFromServer, User.self)

在这种情况下,用户对象将定义名称和电子邮件 = nil

如果你需要从 snake_case 映射到 camelCase 你可以使用编码键

struct User: Decodable {
  let firstName: String
  let lastName: String
  let email: String

  enum CodingKeys: String, CodingKey {
    case email
    case firstName = "first_name"
    case lastName = "last_name"
  }

  init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    email = try values.decode(String.self, forKey: .email)
    firstName = try values.decode(String.self, forKey: .firstName)
    lastName = try values.decode(String.self, forKey: .lastName)
  }
}

希望对你有帮助

关于ios - 如何根据key将JSON解析成不同的模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47220092/

相关文章:

iOS UITableVIew 在多次重新加载时增加单元格大小

android - 应用程序的不同名称(iOS 和 Android)

ios - Swift:添加项目时更改 UICollectionView 中单元格布局的宽度

ios - 使用 URL swift Alamofire 上传视频

ios - 无法登录 QuickBlox iOS 13

swift - 将 pcm 加载到 AVAudioPCMBuffer

swift - 弱小的自己去哪儿了?

alamofire - 使用 Content-MD5 之类的东西扩展 Alamofire

swift - 如何使用alamofire在ios中传递访问 token

iphone - 从 UIViewController 返回 NSString