ios - 如何使用可选的 URL 参数为 GET 请求映射不同的 JSON 响应

标签 ios objective-c mapping restkit restkit-0.20

我需要使用可选的 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"
}

实际返回的对象都是相同类型的(并且根不再有键)。

现在很明显,我的 RKResponseDescriptorRKObjectMapping 无法正确处理这种情况。

我研究过使用 RKDynamicMappingRKRoute 但无法真正了解它们的工作方式或者它们是否适用于我的情况...

最佳答案

您的网址是: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/

相关文章:

python - 使用嵌套 defaultdict 重新分配 pandas 系列值

r - 使用矩阵图 (matplotlib) 作为 map ,使用位置作为位置

ios - Collection View 的单元格未显示在行中

ios - SwiftUI 创建列表

iphone - 如何使 'int'到 'string'具有特殊格式?

ios - WKWebView 不发送 session cookie

objective-c - 运行时 xml/json 生成目录内容

objective-c - 位移编码效率(即巧妙的技巧)

java - 从 JAVA 中的 MAP 打印

objective-c - 迭代 NSTableView 中的 View