用RestKit发布JSON字符串数组

编程入门 行业动态 更新时间:2024-10-26 08:32:56
本文介绍了用RestKit发布JSON字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下对象

@interface MyObject : NSObject @property(nonatomic, copy) NSNumber *objectId; @property(nonatomic, copy) NSArray *tags; // array of strings, e.g. @[@"one", @"two"] @end

我想使用RestKit(0.23版)将请求发布到URL

I would like to POST a request using RestKit (version 0.23) to URL

<base_url>/do_something/:objectId

根据tags属性,请求主体应该只是一个JSON字符串数组,即

The request body should be just a JSON array of strings according to the tags property, i.e.

["one", "two"]

我定义了一条路线.

RKRoute *route = [RKRoute routeWithClass: [MyObject class] pathPattern: do_something/:objectId method: RKRequestMethodPOST]; [objectManager.router.routeSet addRoute: route];

现在,我想创建一个请求

Now, I would like to create a request

[objectManager requestWithObject: instanceOfMyObject method: RKRequestMethodPOST path: nil parameters: nil];

如何配置[RKObjectMapping requestMapping]和如何定义RKRequestDescriptor以获取上面的映射(字符串的JSON数组)?

How should I configure a [RKObjectMapping requestMapping] and how should I define a RKRequestDescriptor to get the mapping above (JSON array of strings)?

我尝试了以下操作:

RKObjectMapping *requestMapping = [RKObjectMapping requestMapping]; [requestMapping addPropertyMapping: [RKAttributeMapping attributeMappingFromKeyPath: @"tags" toKeyPath: nil]]; RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping: requestMapping objectClass: [MyObject class] rootKeyPath: nil method: RKRequestMethodAny];

但是,在RKAttributeMapping中使用nil作为键路径会崩溃.使用任何非null值都会导致请求的主体是JSON字典

However, using nil as key path in RKAttributeMapping crashes. Using any not-nil value results in request its body is a JSON dictionary

{"someKeyPath": ["one", "two"]}

推荐答案

我相信RestKit的设计思路是,您应该发布对象,例如. {"tags": [ "tag1", "tag2" ]}.回应也一样;如果主体不是对象(仅仅是一个原始字符串或数组),RestKit就无法很好地处理它.

I believe RestKit was designed with the mentality you should be posting an object instead, eg. {"tags": [ "tag1", "tag2" ]}. Same with responses; if the body is not an object (and just a raw string or array), RestKit isn't going to handle it well.

话虽如此,您可以自己序列化请求并将其发布到正文.例如:

That being said, you can serialize the request yourself and post it to the body. For example:

NSMutableURLRequest *request = [[objectManager requestWithObject:nil method:RKRequestMethodPOST path:@"do_something/objectId" parameters:nil] mutableCopy]; [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:doableIds options:0 error:nil]]; RKObjectRequestOperation *operation = [objectManager objectRequestOperationWithRequest:request success:nil failure:nil]; [objectManager enqueueObjectRequestOperation:operation];

更多推荐

用RestKit发布JSON字符串数组

本文发布于:2023-10-11 13:48:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1481873.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   字符串   RestKit   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!