restkit,如何在没有对象映射的情况下访问对象
Posted
技术标签:
【中文标题】restkit,如何在没有对象映射的情况下访问对象【英文标题】:restkit, how to access object in response without object mapping 【发布时间】:2015-11-02 06:15:21 【问题描述】:如何在不使用对象映射的情况下访问原始响应 json 数据。我有以下响应数据。它包含一个用于执行查询的nextSyncToken
和一个项目集合(在items
会话中)。
我创建了 Item 对象的对象映射,它表示 items
中的内容。但是,我还需要 nextSyncToken
字段。我如何在没有对象映射的情况下访问它。由于syncToken与对象映射没有关系。我该如何处理。
"kind": "calendar#events",
"nextSyncToken": "COib8eSw78gCEOib8eSw78gCGAU=",
"items": [
"id": "_74rk4cpg84o42b9k8or3gb9k74s34b9p8ks34b9m851kac9m64rk4ci36g",
"created": "2010-04-16T11:09:31.000Z",
"updated": "2010-04-16T11:10:27.487Z",
"summary": "iCal test 1",
"start":
"dateTime": "2010-03-16T21:00:00+08:00"
,
"end":
"dateTime": "2010-03-16T22:00:00+08:00"
,
"id": "_752j2h1j6cq4cba68csjeb9k8p33eba1692k4ba284qj8ea688rj2chh6c",
"status": "confirmed",
"created": "2011-10-18T09:36:02.000Z",
"updated": "2011-10-18T09:36:02.000Z",
"summary": "New Event",
"start":
"dateTime": "2011-10-18T03:45:00+08:00"
,
"end":
"dateTime": "2011-10-18T08:15:00+08:00"
]
我的映射代码:
let eventMapping = RKEntityMapping(forEntityForName: "SGEvent", inManagedObjectStore: managedObjectStore)
eventMapping.addAttributeMappingsFromDictionary([
"id": "identifier",
"summary": "summary",
"created": "createdAt",
"updated": "updatedAt",
"location": "location",
"description": "notes",
"start.date": "allDayStart",
"end.date": "allDayEnd"
])
let startTimeMapping = RKAttributeMapping(fromKeyPath: "start.dateTime", toKeyPath: "startTime")
startTimeMapping.valueTransformer = self.googleDateTransformer
eventMapping.addPropertyMapping(startTimeMapping)
let endTimeMapping = RKAttributeMapping(fromKeyPath: "end.dateTime", toKeyPath: "endTime")
endTimeMapping.valueTransformer = self.googleDateTransformer
eventMapping.addPropertyMapping(endTimeMapping)
eventMapping.identificationAttributes = ["identifier"]
let responseDescriptor = RKResponseDescriptor(mapping: eventMapping, method: .GET,
pathPattern: "calendars/:calendarId/events", keyPath: "items",
statusCodes: RKStatusCodeIndexSetForClass(RKStatusCodeClass.Successful))
objectManager.addResponseDescriptor(responseDescriptor)
我的请求操作:
objectManager.getObjectsAtPath("calendars/\(identifier)/events",
parameters: [self.ACCESS_TOKEN: accessToken], success: (operation, results) -> Void in
callback?(results: nil, error: nil)
) (_, error) -> Void in
print(error)
【问题讨论】:
【参考方案1】:通常您会添加其他具有适当映射的响应描述符来处理此问题。
使用objectManager.getObjectsAtPath
时,您可以获得原始数据,假设您有一些其他响应描述符会导致成功块被调用,方法是导航到 HTTP 操作中的响应数据(然后您可以将其解压缩)你觉得合适):
operation.HTTPRequestOperation.responseData
(或使用responseString
代替responseData
)。
【讨论】:
你能举个例子吗?我对 RestKit 和 ios 很陌生 这就是在成功块中获取响应数据的所有代码,然后将其与 JSON 序列化程序或类似程序一起使用。【参考方案2】: if let dict = try? NSJSONSerialization.JSONObjectWithData(operation.HTTPRequestOperation.responseData, options: .AllowFragments) as? [String: AnyObject],
let nextSyncToken = dict?["nextSyncToken"] as? String
print(nextSyncToken)//get the nextSyncToken
【讨论】:
以上是关于restkit,如何在没有对象映射的情况下访问对象的主要内容,如果未能解决你的问题,请参考以下文章