RestKit:如何发布对象数组? [英] RestKit: How does one post an array of objects?

查看:139
本文介绍了RestKit:如何发布对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题摘要

考虑一个类别 SyncObject 具有以下属性: time someValue lastChange uuid

Consider a class SyncObject that is KVC-compliant with properties such as: time, someValue, lastChange, uuid.

考虑一个 NSArray SyncObject

我需要将数组作为JSON数组提交到服务器。

I need to submit the array to the server as a JSON array.

如何使用RestKit使用HTTP POST将此数组提交到服务器?

How would one submit this array to the server using HTTP POST using RestKit?

示例数组:

[
  {
    "time": "14:45 10/21/2011",
    "someValue": "15",
    "lastChange": "14:45 10/21/2011",
    "uuid": "0b07c510-f4c8-11e0-be50-0800200c9a66"
  },
  {
    "time": "14:50 10/21/2011",
    "someValue": "62",
    "lastChange": "14:51 10/21/2011",
    "uuid": "1a6d4480-f4c8-11e0-be50-0800200c9a66"
  }
]






详细

我需要到服务器作为JSON。在我看来,RestKit是最简单的方法:我试图避免将对象转换为一组 NSDictionary 对象,然后使用一些JSON编码器JSON,我可以 POST 到服务器。

I have an array of objects that I need to the server as JSON. It seems to me that RestKit is the easiest way to do this: I'm trying to avoid converting objects into a set of NSDictionary objects, and then using some JSON encoder to get JSON which I can POST to the server.

所以,创建了数组,对于存储在数组中的对象类,我自然尝试 POST 到服务器。

So, having created the array, and having set up the mapping for the class of objects stored in the array, I naturally try to POST to the server.

RKObjectManager* mgr = [RKObjectManager objectManagerWithBaseURL:@"http://localhost/someweb/api/"];
mgr.serializationMIMEType = RKMIMETypeFormURLEncoded;
mgr.client.username = @"username";
mgr.client.password = @"password";
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]];
[mapping mapKeyPath: @"time"       toAttribute:@"time"         ];  
[mapping mapKeyPath: @"someValue"  toAttribute:@"someValue"    ];
[mapping mapKeyPath: @"lastChange" toAttribute:@"lastChange"   ];
[mapping mapKeyPath: @"uuid"       toAttribute:@"uuid"         ];
RKObjectMapping* mappingForSerialization = [mapping inverseMapping];
[mgr.mappingProvider setSerializationMapping:mappingForSerialization 
                                    forClass:[NSManagedObject class]];

[mgr.router routeClass:[NSManagedObject class] toResourcePath:@"/sync" forMethod:RKRequestMethodPOST];    

[mgr postObject:array delegate:nil/*self*/];

但是,这是我得到的:


2011-10-11 14:57:51.769 AppConnect[1974:6e0b] *** Terminating app due to uncaught exception '(null)', reason: 'Unable to find a routable path for object of type '__NSArrayI' for HTTP Method 'POST''

显然,RestKit不知道如何处理 NSArray s。

Apparently, RestKit does not know how to handle NSArrays.

如何使用RestKit发布对象数组?

我尝试过不同的东西:我用一个手动发送通过 RKObjectLoader 替换了最后一行。

I've tried something different: I replaced the last line with a manual send through RKObjectLoader.

//[mgr postObject:[NSMutableDictionary dictionaryWithObject:array forKey:@"data"] delegate:nil/*self*/];


NSString* syncPath = @"/sync"; 
RKObjectLoader * objectLoader = [mgr objectLoaderWithResourcePath:syncPath delegate:self];
objectLoader.serializationMIMEType = RKMIMETypeJSON;
objectLoader.method = RKRequestMethodPOST;
//objectLoader.objectClass = [NSManagedObject class];       
//objectLoader.managedObjectStore = mgr.objectStore; 
objectLoader.params = [NSDictionary dictionaryWithObject:array 
                                                  forKey:@"MyData"]; 
[objectLoader send];

不幸的是,这不会应用任何排序的映射,而是传输对象的描述数组。设置 serializationMIMEType 也不会影响传输内容的结构, params 始终以 application / x-www-form-urlencoded

Unfortunately, this does not apply mapping of any sort, and instead transmits an array of objects' descriptions. Setting serializationMIMEType also does not affect the structure of transmitted contents, and params are always transmitted as application/x-www-form-urlencoded.

我还尝试分配序列化映射并将对象作为 targetObject sourceObject (这似乎是RestKit内部在 - [RKObjectManager postObject:delegate:] )。

I also tried assigning serialization mapping and passing the object as targetObject and sourceObject (this seems to be what RestKit does internally in -[RKObjectManager postObject:delegate:]).

RKObjectLoader * objectLoader = [mgr objectLoaderWithResourcePath:syncPath delegate:self];
objectLoader.method = RKRequestMethodPOST;
//objectLoader.objectClass = [NSManagedObject class];       
//objectLoader.managedObjectStore = mgr.objectStore; 
objectLoader.params = [NSMutableDictionary dictionaryWithObject:array 
                                                  forKey:@"MyData"]; 
objectLoader.serializationMapping = mapping;
objectLoader.serializationMIMEType = RKMIMETypeJSON;
objectLoader.sourceObject = objectLoader.params;
objectLoader.targetObject = objectLoader.params;
[objectLoader send];

不幸的是,这种方式没有映射:

Unfortunately, no mapping occurs this way:

2011-10-12 12:36:48.143 MyProject[5119:207] D restkit.network:RKObjectLoader.m:290 POST or PUT request for source object {
    MyData =     (
        "<NSManagedObject: 0x5935430> (entity: SomeRecord; id: 0x5934da0 <x-coredata://64DF9977-DA50-4FCD-8C20-4132E58439BF/SomeRecord/p1> ; data: <fault>)",
        "<NSManagedObject: 0x5935730> (entity: SomeRecord; id: 0x5934db0 <x-coredata://64DF9977-DA50-4FCD-8C20-4132E58439BF/SomeRecord/p2> ; data: <fault>)"
    );
}, serializing to MIME Type application/json for transport...
2011-10-12 12:36:48.143 MyProject[5119:207] D restkit.object_mapping:RKObjectMappingOperation.m:428 Starting mapping operation...
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'time'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'someValue'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'lastChange'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'uuid'
2011-10-12 12:36:48.145 MyProject[5119:207] D restkit.object_mapping:RKObjectMappingOperation.m:448 Mapping operation did not find any mappable content
2011-10-12 12:36:48.146 MyProject[5119:207] T restkit.network:RKRequest.m:211 Prepared POST URLRequest '<NSMutableURLRequest http://someurl/api/sync?request=provide_key>'. HTTP Headers: {
    Accept = "application/json";
    "Content-Length" = 0;
}. HTTP Body: .


推荐答案

restkit不支持NSArray的可路径路径,因为您定义了 NSManagedObject 类的路由。您可能想创建一个自定义类,例如 MySyncEntity ,它包含您在映射中定义的ivar。然后,你创建你的映射如下:

The restkit does not fund routable path for NSArray, because you defined your routing for NSManagedObject class. You probably want to create a custom class, say MySyncEntity that holds the ivars you define in your mapping. Then, you create your mapping like this:

RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[MySyncEntity class]];
....
[myManager setSerializationMIMEType:RKMIMETypeJSON];
[[myManager router] routeClass:[MySyncEntity class] toResourcePath:@"/sync"];

那么您应该能够将对象作为JSON对象发布到API后端。

then you should be able to post your object to the API backend as JSON object.

进一步说明:

在这种情况下,我们要发布一个 NSManagedObject 实例转换为基于JSON的API。为了做到这一点,我们需要创建一个同步实体,它保存数组中的对象:

In this case, we want to post an array of NSManagedObject instances into a JSON based API. To do that we need to create a sync entity, that holds the objects in an array:

@interface MySyncEntity : NSObject {}
@property (nonatomic, retain) NSArray* mySyncArray;
...
@end 

mySyncArray 将保存我们想要提交给其余后端的有效负载。然后,我们为 mySyncArray MySyncEntity中发送的 NSManagedObject 创建适当的映射实体本身。

The mySyncArray will hold the payload we'd like to submit to the rest backend. Then, we create appropriate mapping for both NSManagedObject that will be sent in mySyncArray and the MySyncEntity entity itself.

RKObjectManager *manager = [RKObjectManager objectManagerWithBaseURL:kBaseUrl];
...
RKObjectMapping *mngObjMapping = [RKObjectMapping mappingForClass:[NSManagedObject class]]; 
[mngObjMapping mapKeyPath: @"time" toAttribute:@"time"];  
[mngObjMapping mapKeyPath: @"recordLevel" toAttribute:@"recordLevel"];
.... //map as many properties as you wish
[[manager mappingProvider] setSerializationMapping:[mngObjMapping inverseMapping]
                                          forClass:[NSManagedObject class]];

//now, we create mapping for the MySyncEntity
RKObjectMapping *syncEntityMapping = [RKObjectMapping mappingForClass:[MySyncEntity class]];
[syncEntityMapping mapKeyPath:@"mySyncArray" toRelationship:@"mySyncArray" withMapping:mngObjMapping];
[[manager mappingProvider] setSerializationMapping:[syncEntityMapping inverseMapping]
                                          forClass:[MySyncEntity class]];

现在定义了映射,我们可以将对象发布到服务器

Now with the mappings defined we can post the object to the server

[manager postObject:mySyncInstance delegate:nil];

mySyncInstance 数组的内容将被映射根据 mngObjMapping 并发送到定义的休止端点。

The contents of mySyncInstance array will be mapped according to mngObjMapping and sent to defined rest endpoint.

这篇关于RestKit:如何发布对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆