我需要使用可选的 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”NSObject 组成的 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/