我正在发送一个包裹在铁 mq 消息中的 json blob。
它涉及到 Restkit 作为:
{
id:"2837409187409328",
delay:60,
body:"{ myJson:{ "hey":true}}"
}
我使用 rkrelationship 将子对象与主体映射:作为类型自定义对象。
但是,当 Restkit 尝试映射到该自定义对象时,它会爆炸,因为它将该"正文"视为 NSString 而不是 NSDictionary,并尝试通过使用 sourceKeyPath 从生成的源对象中获取值...但由于它是NSString,它爆炸了。 跟:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x7fcf91165060> valueForUndefinedKey:]: this class is not key value coding-compliant for the key alreadyLiked.'
我尝试使用动态映射并用 NSDictionary 替换表示。
我尝试按照文档中的建议对访问器进行验证,但从未调用该代码。有什么想法吗?
通过后处理解决。我最终获取了传递到正文中的字符串,覆盖了该 body 属性的 setter,并在该 setter 中运行映射操作来获取 json 字符串,并将其映射到我的自定义对象(转换为字典后),然后在我的父对象上设置它。
希望对您有所帮助!
//here I have an object with a string property called Body that contains JSON.
//I extract the json, turn it into a dictionary then map it to another property on that same object that actually has a relationship mapping...
//always check to see if the body actually exists before you try to map it
//otherwise you will have a crash in your overridden setter..
if(self.Body){
NSData *data = [self.Body dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *representation = json;
//NSDictionary *metadata = @{ @"URL": [NSURL URLWithString:@"http://restkit.org"]http://restkit.org"] };
RKObjectMapping *objectMapping = [MyObject mapping];
RKMappingOperation *operation = [[RKMappingOperation alloc] initWithSourceObject:representation destinationObject:mappedResultDTO mapping:objectMapping];
RKObjectMappingOperationDataSource *dataSource = [RKObjectMappingOperationDataSource new];
operation.dataSource = dataSource;
// [operation start];
NSError *error = nil;
BOOL success = [operation performMapping:&error];
}