我需要使用可选的 URL 参数对 url 执行 GET 请求。
基本 URL 类似于 http://host/user/explore
,可以选择查询 http://host/user/explore?who=VALUE&category=VALUE&service= VALUE
以获得更准确的结果。
对于第一种情况,响应带有根键,例如:
{
"professionals": [
{
"_id": "59e8576cb524cf44a435844b"
}
],
"salons": [
{
"_id": "59e857bbb524cf44a4358454"
}
]
}
而且我可以通过设置我的响应描述符来成功映射响应,例如:
RKResponseDescriptor *response = [RKResponseDescriptor
responseDescriptorWithMapping:[Explore map1]
method:RKRequestMethodGET
pathPattern"user/explore"
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
return response;
(请注意,[Explore map1]
用于映射“Professional”的 NSArray 和另一个由“Salon”NSObjects 组成的 NSArray)
但是,当我查询 http://host/user/explore?who=VALUE&category=VALUE&service=VALUE
时,我的响应 JSON 变为:
{
"_id": "59f6f9fc36e51720da2e85f4"
},
{
"_id": "92x2f9fc36e51720da2e66d5"
}
实际返回的对象都是相同的类型(并且不再在根处有键)。
所以现在很明显,我的 RKResponseDescriptor
和 RKObjectMapping
未能正确处理这种情况。
我已经研究过使用 RKDynamicMapping
或 RKRoute
并且无法真正了解它们的工作原理,或者它们是否适用于我的情况...
你的网址是:http://host/user/explore?who=VALUE&category=VALUE&service=VALUE 所以就这样做吧:
let postMapping: RKObjectMapping = RKObjectMapping(for: GetFoo.self)
postMapping.addAttributeMappings(from:["who","category","service"])
// Define response decriptor
let statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClass.successful)
let resDescriptor = RKResponseDescriptor(mapping: postMapping, method: RKRequestMethod.GET, pathPattern: "user/explore", keyPath: nil, statusCodes: statusCodes)
// Create object manager
let url = URL(string: "http://host")
let jsonPlaceholderManager = RKObjectManager(baseURL: url)
jsonPlaceholderManager?.addResponseDescriptor(resDescriptor)
RKObjectManager.setShared(jsonPlaceholderManager)
RKObjectManager.shared().getObjectsAtPath("/user/explore?who=VALUE&category=VALUE&service=VALUE", parameters: nil, success: { (operation, mappingResult) -> Void in
let dataResponse = operation?.httpRequestOperation.responseData
let jsonData = try? JSONSerialization.jsonObject(with: dataResponse!, options: .mutableContainers) as? NSMutableDictionary
print(dataResponse)
关于ios - 如何为带有可选 URL 参数的 GET 请求映射不同的 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47148874/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |