关于ios:ObjectMapper failed to serialize response error Code=2

ObjectMapper failed to serialize response error Code=2

我在使用 Alamofire 对象映射器

访问 Alamofire 获取请求时遇到错误

这就是我使用 API 的方式-

1
2
3
4
5
6
7
8
APIService.shared.getSlots{ (success,weekSlots, error) in
    if success {
    self.weekSlots = weekSlots!
    print("success!!")
  } else {
    print(error?.errorMessage ??"NOPE")
  }
}

而APIService类中的getSlot函数是-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
open func getSlots(completion: @escaping (Bool, [WeekSlot]?, APIError?) -> ()) {
sessionManager.request(APIRouter.getSlots())
  .validate(statusCode: 200..<300)
  .responseArray(queue: nil,
                  keyPath:"week_slots",
                  context: nil) { (response: DataResponse<[WeekSlot]>) in
                    switch response.result {
                    case .success(let value):
                      self.saveArraysToRealm(value: value)
                      completion(true,value, nil)
                    case .failure:
                      let error = self.processFailure(json: JSON(response.data as Any))
                      completion(false, nil, error)
                      print(error)
                    }
  }
}

这是我的数据模型:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import Foundation
import ObjectMapper
import RealmSwift

class WeekSlot: Object, Mappable {
  dynamic var date : String? =""
  var slot = List<Slots>()

  //Impl. of Mappable protocol
  required convenience init?(map: Map) {
  self.init()
  }

  func mapping(map: Map) {
    date <- map["date"]
    slot <- (map["slots"], ArrayTransform<Slots>())
  }
}

我已经声明了执行get请求的请求,并且url也是正确的。 API 不接受任何参数,除了由 sessionManager 处理的身份验证令牌。但是,我在调试时收到以下错误响应-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
[Request]: GET http://beta.xamidea.in/api/v1/teachers/get_slots/
[Response]: <NSHTTPURLResponse: 0x600000434c80> { URL: http://beta.xamidea.in/api/v1/teachers/get_slots/ } { status code: 200, headers {
Allow ="GET, POST, HEAD, OPTIONS";
Connection ="keep-alive";
"Content-Length" = 477;
"Content-Type" ="application/json";
Date ="Tue, 10 Oct 2017 11:01:53 GMT";
Server ="nginx/1.10.3 (Ubuntu)";
Vary = Accept;
"X-Frame-Options" = SAMEORIGIN;
} }
[Data]: 477 bytes
[Result]: FAILURE: Error Domain=com.alamofireobjectmapper.error Code=2   "ObjectMapper failed to serialize response." UserInfo=.   {NSLocalizedFailureReason=ObjectMapper failed to serialize response.}
[Timeline]: Timeline: {"Request Start Time": 529326113.851,"Initial  Response Time": 529326113.985,"Request Completed Time": 529326113.986,  "Serialization Completed Time": 529326113.987,"Latency": 0.134 secs,   "Request Duration": 0.135 secs,"Serialization Duration": 0.001 secs,  "Total Duration": 0.136 secs }
  a–? request : Optional<URLRequest>
a–? some : http://beta.xamidea.in/api/v1/teachers/get_slots/
  a–? url : Optional<URL>
    a–? some : http://beta.xamidea.in/api/v1/teachers/get_slots/
  – cachePolicy : 0
  – timeoutInterval : 60.0
  – mainDocumentURL : nil
  – networkServiceType : __ObjC.NSURLRequest.NetworkServiceType
  – allowsCellularAccess : true
  a–? httpMethod : Optional<String>
    – some :"GET"
  a–? allHTTPHeaderFields : Optional<Dictionary<String, String>>
    a–? some : 1 element
      a–? 0 : 2 elements
        – key :"Authorization"
        – value :"Token 4d7ebe501bcd7c910cf1950ab53bc8aa2a4a569d"
  – httpBody : nil
  – httpBodyStream : nil
  – httpShouldHandleCookies : true
  – httpShouldUsePipelining : false
  a–? response : Optional<NSHTTPURLResponse>
  a–? data : Optional<Data>
a–? some : 477 bytes
  – count : 477
  a–? pointer : 0x00007f896a48aa80
    – pointerValue : 140228170394240
  a–? result : FAILURE: Error Domain=com.alamofireobjectmapper.error  Code=2"ObjectMapper failed to serialize response." UserInfo= {NSLocalizedFailureReason=ObjectMapper failed to serialize response.}
  a–? timeline : Timeline: {"Request Start Time": 529326113.851,"Initial Response Time": 529326113.985,"Request Completed Time": 529326113.986,"Serialization Completed Time": 529326113.987,"Latency": 0.134 secs,"Request Duration": 0.135 secs,"Serialization Duration": 0.001 secs,"Total Duration": 0.136 secs }
– requestStartTime : 529326113.85062999
– initialResponseTime : 529326113.98505801
– requestCompletedTime : 529326113.98612601
– serializationCompletedTime : 529326113.986781
– latency : 0.13442802429199219
– requestDuration : 0.13549602031707764
– serializationDuration : 0.00065499544143676758
– totalDuration : 0.1361510157585144
  a–? _metrics : Optional<AnyObject>

这个错误是什么意思??

API 对成功的响应是这样的-

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
  {
   "result": {
       "week_slots": [
            {
               "date":"2017-10-10",
               "slots": []
        },
        {
           "date":"2017-10-11",
           "slots": [
                {
                   "start":"2017-10-11T20:00:00Z",
                   "end":"2017-10-11T21:00:00Z",
                   "availability": true,
                   "booked": false
                },
                {
                   "start":"2017-10-11T10:00:00Z",
                   "end":"2017-10-11T12:00:00Z",
                   "availability": true,
                   "booked": false
                }
            ]
        },
        {
           "date":"2017-10-12",
           "slots": []
        },
        {
           "date":"2017-10-13",
           "slots": []
        },
        {
           "date":"2017-10-14",
           "slots": []
        },
        {
           "date":"2017-10-15",
           "slots": []
        },
        {
           "date":"2017-10-16",
           "slots": []
        }
    ]
},
"success": true,
"error": {}
}

我在 1 天后找到了解决方案,问题在于 keyPath 访问”week_slots” ,因为我使用 swiftyjson 访问的正确方法是:

1
keyPath:"result.week_slots"

所以基本上每当你得到这个错误时,即使响应是成功的,这是因为你无法在你的模型中正确映射响应


尝试将模型类更改为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class WeekSlot: Object, Mappable {
   dynamic var date : String? =""
   var slot: [Slots] = []

   //Impl. of Mappable protocol
   required convenience init?(map: Map) {
   self.init()
   }

  func mapping(map: Map) {
   date <- map["date"]
   slot <- map["slots"]
  }
}

还要检查您的插槽型号


原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/268695.html

(0)
上一篇 2022年6月20日
下一篇 2022年6月20日

相关推荐

发表回复

登录后才能评论