ios - 如何为带有可选 URL 参数的 GET 请求映射不同的 JSON 响应
<p><p>我需要使用可选的 URL 参数对 url 执行 GET 请求。 </p>
<p>基本 URL 类似于 <code>http://host/user/explore</code>,可以选择查询 <code>http://host/user/explore?who=VALUE&category=VALUE&service= VALUE</code> 以获得更准确的结果。</p>
<p>对于第一种情况,响应带有根键,例如:</p>
<pre><code>{
"professionals": [
{
"_id": "59e8576cb524cf44a435844b"
}
],
"salons": [
{
"_id": "59e857bbb524cf44a4358454"
}
]
}
</code></pre>
<p>而且我可以通过设置我的响应描述符来成功映射响应,例如:</p>
<pre><code>RKResponseDescriptor *response = [RKResponseDescriptor
responseDescriptorWithMapping:
method:RKRequestMethodGET
pathPattern:@"user/explore"
keyPath:nil
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
return response;
</code></pre>
<p>(请注意,<code></code> 用于映射“Professional”的 NSArray 和另一个由“Salon”NSObjects 组成的 NSArray)</p>
<p>但是,当我查询 <code>http://host/user/explore?who=VALUE&category=VALUE&service=VALUE</code> 时,我的响应 JSON 变为:</p>
<pre><code>{
"_id": "59f6f9fc36e51720da2e85f4"
},
{
"_id": "92x2f9fc36e51720da2e66d5"
}
</code></pre>
<p>实际返回的对象都是相同的类型(并且不再在根处有键)。 </p>
<p>所以现在很明显,我的 <code>RKResponseDescriptor</code> 和 <code>RKObjectMapping</code> 未能正确处理这种情况。</p>
<p>我已经研究过使用 <code>RKDynamicMapping</code> 或 <code>RKRoute</code> 并且无法真正了解它们的工作原理,或者它们是否适用于我的情况...</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>你的网址是:<a href="http://host/user/explore?who=VALUE&category=VALUE&service=VALUE" rel="noreferrer noopener nofollow">http://host/user/explore?who=VALUE&category=VALUE&service=VALUE</a>
所以就这样做吧:</p>
<pre><code> 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)
</code></pre></p>
<p style="font-size: 20px;">关于ios - 如何为带有可选 URL 参数的 GET 请求映射不同的 JSON 响应,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/47148874/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/47148874/
</a>
</p>
页:
[1]