2012-10-05 83 views
0

我的JSON的結構如下:錯誤設置RestKit

{ 
"<Person>k__BackingField" =  { 
    "_email" = "[email protected]"; 
    "_emailUpdate" = 1; 
    "_firstName" = "First"; 
    "_lastName" = "Last"; 
}; 
"<SharedKey>k__BackingField" = "some-long-random-string"; 
} 

我使用restkit登錄的這個人。它創建郵政,並正確地獲得該響應。我的映射設置如下:

+(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

你沒有響應字符串轉換成JSON對象,然後將它傳遞給RKObjectMapper。您傳遞的響應字符串值不響應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]; 
    } 
};