RestKit:如何发布一个对象数组?

时间:2011-10-11 13:01:38

标签: objective-c ios cocoa-touch restkit

问题摘要:

考虑与KVC兼容的课程SyncObject,其中包含以下属性:timesomeValuelastChangeuuid

考虑NSArray仅包含SyncObject的实例。

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

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

示例数组:

[
  {
    "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到服务器。

因此,在创建了数组并设置了存储在数组中的对象类的映射之后,我自然会尝试POST到服务器。

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

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


我尝试了不同的方法:我通过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传输。

我还尝试分配序列化映射并将对象传递为targetObjectsourceObject(这似乎是RestKit在-[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];

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

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: .

2 个答案:

答案 0 :(得分:18)

restkit不为NSArray的可路由路径提供资金,因为您为NSManagedObject类定义了路由。您可能想要创建一个自定义类,比如MySyncEntity,它包含您在映射中定义的ivars。然后,您可以像这样创建映射:

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

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

进一步澄清:

在这种情况下,我们希望将一个NSManagedObject实例数组发布到基于JSON的API中。为此,我们需要创建一个同步实体,将对象保存在数组中:

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

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

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]];

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

[manager postObject:mySyncInstance delegate:nil];

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

答案 1 :(得分:3)

作为进一步的澄清,我想指出在mja's answer中关键是

[syncEntityMapping mapKeyPath:@"mySyncArray" toRelationship:@"mySyncArray" withMapping:mngObjMapping];

这表示“mySyncArray密钥路径是一个数组,其中包含应根据mngObjMapping”映射的对象。