Swift:无法解析JSON响应模型

时间:2019-02-26 08:35:28

标签: json swift alamofire objectmapper

我正在从服务器获取数据响应,如下所示:

{
   "success": true,
   "data": {
      "cash": 0,
      "newCash": 0,
      "cashExpireAt": "2019-02-26T16:01:35.6451887+08:00",
      "isEnabled": false,
      "low_balance": true
    }
}

//下面是模型类

class WalletBalance: Mappable {

   var isSuccess               : Bool! = false
   var data                    : WalletData?

   required init?(map: Map) {
      //Code here
   }

   func mapping(map: Map) {
      isSuccess <- map["success"]
      data <- map["data"]
   }
}

class WalletData: Mappable {

   var cash                     : Int! = 0
   var newCash                  : Int! = 0
   var cashExpireAt             : String! = ""
   var isEnabled                : Bool! = false
   var low_balance              : Bool! = false

   required init?(map: Map) {
      //Code here
   }

   func mapping(map: Map) {
      cash <- map["cash"]
      newCash <- map["newCash"]
      cashExpireAt <- map["cashExpireAt"]
      isEnabled <- map["isEnabled"]
      low_balance <- map["low_balance"]
   }
}

//以下是调用服务器api的代码

Alamofire.request(url!, method: .get, parameters: nil, encoding: URLEncoding.default, headers: walletHeaders)
    .validate(statusCode: 200..<600)
    .responseObject { (response: DataResponse<WalletBalance>) in
         switch response.result {
         case .success:
            if response.result.value == nil {
               //Code here
            } else {
               completion(response.result.value!)
            }
         break
         case .failure(let error):
            print("error: ", error.localizedDescription)
         break
       }
     }

我遇到错误:

  

错误:操作无法完成。 ObjectMapper失败   序列化响应。

我尝试使用邮递员调用api,但在邮递员中可以正常工作。

2 个答案:

答案 0 :(得分:1)

您是否尝试过使用Decodable而不是Alamofire documentation建议的Mappable

答案 1 :(得分:1)

使用Decodable。它更加简单,高效,内置,并且生成的代码更少。日期可以直接解码为Date

let jsonString = """
{
  "success": true,
  "data": {
    "cash": 0,
    "newCash": 0,
    "cashExpireAt": "2019-02-26T16:01:35.6451887+08:00",
    "isEnabled": false,
    "low_balance": true
  }
}
"""

struct Balance : Decodable {
    let success : Bool
    let data : Wallet
}

struct Wallet: Decodable {
    let cash, newCash : Int
    let cashExpireAt : Date
    let isEnabled, lowBalance : Bool
}


let data = Data(jsonString.utf8)
let decoder = JSONDecoder()

let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
decoder.dateDecodingStrategy = .formatted(dateFormatter)
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
    let result = try decoder.decode(Balance.self, from: data)
    print(result)
} catch { print(error) }