设置RestKit时出错

时间:2012-10-05 13:13:53

标签: objective-c ios restkit

我的JSON具有以下结构:

{
"<Person>k__BackingField" =     {
    "_email" = "name@domain.com";
    "_emailUpdate" = 1;
    "_firstName" = "First";
    "_lastName" = "Last";
};
"<SharedKey>k__BackingField" = "some-long-random-string";
}

我正在使用restkit作为此人登录。它创建了Post,并正确地获得了响应。我的映射设置如下:

+(void)ConfigureAPI
{
[super ConfigureAPI];
// Initialize RestKit
[RKObjectManager managerWithBaseURLString: @"www.api_root.com/";
Class<RKParser> parser = [[RKParserRegistry sharedRegistry] parserClassForMIMEType:@"application/json"];
[[RKParserRegistry sharedRegistry] setParserClass:parser forMIMEType:@"text/plain"];

RKObjectMapping *mapping;

// Person
mapping = [RKObjectMapping mappingForClass:[Person class]];
[mapping mapKeyPath:@"_email" toAttribute:@"email"];
[mapping mapKeyPath:@"_emailUpdate" toAttribute:@"emailUpdate"];
[mapping mapKeyPath:@"_firstName" toAttribute:@"firstName"];
[mapping mapKeyPath:@"_lastName" toAttribute:@"lastName"];
[[RKObjectManager sharedManager].mappingProvider setMapping:mapping forKeyPath:@"<Person>k__BackingField"];
}

当我运行应用程序并调用获取JSON响应的函数时,我收到以下错误:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x7b41800> valueForUndefinedKey:]: this class is not key value coding-compliant for the key <Person>k__BackingField.'

有人知道我为什么会这样吗?一切似乎都设置正确

修改

如果它有帮助,这就是我处理响应的方式:

    // when you get the response...
    request.onDidLoadResponse = ^(RKResponse *response){
        RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:[response bodyAsString] mappingProvider:[RKObjectManager sharedManager].mappingProvider];

        Person *person = nil;
        RKObjectMappingResult *mappingResult = [mapper performMapping];
        person = [mappingResult asObject];
    };

1 个答案:

答案 0 :(得分:1)

在将响应字符串传递给RKObjectMapper之前,您不会将其转换为JSON对象。您传入了响应的字符串值,该值不响应valueForKey:,这解释了您获得的异常。您可以轻松地将其转换为如下对象:

request.onDidLoadResponse = ^(RKResponse *response){

    NSError *error;
    id jsonObject = [response parsedBody:&error];

    if(error)
        NSLog(@"Error parsing JSON: %@", error.localizedDescription);
    else {
        RKObjectMapper *mapper = [RKObjectMapper mapperWithObject:jsonObject mappingProvider:[RKObjectManager sharedManager].mappingProvider];

        Person *person = nil;
        RKObjectMappingResult *mappingResult = [mapper performMapping];
        person = [mappingResult asObject];
    }
};