草庐IT

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

codeneng 2023-03-28 原文

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"]
  }
}

还要检查您的插槽型号

有关关于ios:ObjectMapper failed to serialize response error Code=2的更多相关文章

  1. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  2. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  3. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  4. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  5. ruby-on-rails - 关于 Ruby 的一般问题 - 2

    我在我的rails应用程序中安装了来自github.com的acts_as_versioned插件,但有一段代码我不完全理解,我希望有人能帮我解决这个问题class_eval我知道block内的方法(或任何它是什么)被定义为类内的实例方法,但我在插件的任何地方都找不到定义为常量的CLASS_METHODS,而且我也不确定是什么here,并且有问题的代码从lib/acts_as_versioned.rb的第199行开始。如果有人愿意告诉我这里的内幕,我将不胜感激。谢谢-C 最佳答案 这是一个异端。http://en.wikipedia

  6. ruby - 我怎样才能更好地了解/了解更多关于 Ruby 的知识? - 2

    按照目前的情况,这个问题不适合我们的问答形式。我们希望答案得到事实、引用或专业知识的支持,但这个问题可能会引发辩论、争论、投票或扩展讨论。如果您觉得这个问题可以改进并可能重新打开,visitthehelpcenter指导。关闭9年前。我最近开始学习Ruby,这是我的第一门编程语言。我对语法感到满意,并且我已经完成了许多只教授相同基础知识的教程。我已经写了一些小程序(包括我自己的数组排序方法,在有人告诉我谷歌“冒泡排序”之前我认为它非常聪明),但我觉得我需要尝试更大更难的东西来理解更多关于Ruby.关于如何执行此操作的任何想法?

  7. ruby - 关于 Ruby 中 Dir[] 和 File.join() 的混淆 - 2

    我在Ruby中遇到了一个关于Dir[]和File.join()的简单程序,blobs_dir='/path/to/dir'Dir[File.join(blobs_dir,"**","*")].eachdo|file|FileUtils.rm_rf(file)ifFile.symlink?(file)我有两个困惑:首先,File.join(@blobs_dir,"**","*")中的第二个和第三个参数是什么意思?其次,Dir[]在Ruby中有什么用?我只知道它等价于Dir.glob(),但是,我对Dir.glob()确实不是很清楚。 最佳答案

  8. elasticsearch源码关于TransportSearchAction【阶段三】 - 2

    1.回顾.TransportServicepublicclassTransportServiceextendsAbstractLifecycleComponentTransportService:方法:1publicfinalTextendsTransportResponse>voidsendRequest(finalTransport.Connectionconnection,finalStringaction,finalTransportRequestrequest,finalTransportRequestOptionsoptions,TransportResponseHandlerT>

  9. 关于Qt程序打包后运行库依赖的常见问题分析及解决方法 - 2

    目录一.大致如下常见问题:(1)找不到程序所依赖的Qt库version`Qt_5'notfound(requiredby(2)CouldnotLoadtheQtplatformplugin"xcb"in""eventhoughitwasfound(3)打包到在不同的linux系统下,或者打包到高版本的相同系统下,运行程序时,直接提示段错误即segmentationfault,或者Illegalinstruction(coredumped)非法指令(4)ldd应用程序或者库,查看运行所依赖的库时,直接报段错误二.问题逐个分析,得出解决方法:(1)找不到程序所依赖的Qt库version`Qt_5'

  10. ruby - 为 IO::popen 拯救 "command not found" - 2

    当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby​​1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#

随机推荐