Swift/Alamofire/ObjectMapper:忽略零值

Posted

技术标签:

【中文标题】Swift/Alamofire/ObjectMapper:忽略零值【英文标题】:Swift/Alamofire/ObjectMapper: Ignore nil values 【发布时间】:2019-09-05 11:36:30 【问题描述】:

只是想知道这是否可能,因为我试图避免创建重复/非常相似的模型。

例如,如果我有以下 JSON:

 
  "1001": 
    "first_name": "James",
    "last_name": "Smith",
    "age": 30,
  
  "1002": 
    "first_name": "Sarah",
    "last_name": "Jones",
  

我有以下类来映射用户数据:

class UserModel: Mappable 

  var firstName: String?
  var lastName: String?
  var age: Int?

  required init?(map: Map) 

  func mapping(map: Map) 
      start           <- map["first_name"]
      current         <- map["last_name"]
      stage           <- map["age"]
  


这很好用,除了打印出响应之外,我会得到以下信息:


  
    "firstName" : "James",
    "lastName"  : "Smith",
    "age"       : 30
  
  
    "firstName" : "Sarah",
    "lastName"  : "Jones",
    "age"       : nil
  

有没有办法在发出请求时忽略任何nil 值?试图避免创建另一个年龄已删除的UserModel,而宁愿保留一个模型,而只是忽略我知道不会出现在响应中的键。

【问题讨论】:

成为1001" 无效1001"1001" 然后[Int:Model][String:Model] 分别 【参考方案1】:

您可以改用Codable

struct Model : Codable 
  let firstName,lastName:String
  let age:Int?
 

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase 
let res = try? decoder.decode([String:Model].self,from:data)

【讨论】:

【参考方案2】:

试试这个:

struct UserModelValue: Codable, Equatable 
    let firstName: String?
    let lastName: String?
    let age: Int?

    enum CodingKeys: String, CodingKey 
        case firstName = "first_name"
        case lastName = "last_name"
        case age = "age"
    

    init(firstName: String?, lastName: String?, age: Int?) 
        self.firstName = firstName
        self.lastName = lastName
        self.age = age
    


typealias UserModel = [String: UserModelValue]

【讨论】:

以上是关于Swift/Alamofire/ObjectMapper:忽略零值的主要内容,如果未能解决你的问题,请参考以下文章