2011-12-28 159 views
2

我想通過使用RestKit從我的自定義對象中獲取JSON格式字符串。RestKit:serializedObjectForMIMEType失敗,錯誤

這裏是我的代碼:

@interface MyPhoneModel : NSObject 

@property (nonatomic, copy) NSString *number; 
@property (nonatomic, copy) NSString *tag; 

@end 

@interface MyContactModel : NSObject 

@property (nonatomic, copy) NSString *name; 
@property (nonatomic, copy) NSArray *phoneList; 

@end 

- (NSString *)jsonString:(MyContactModel *)contact 
{ 
    RKObjectMapping *phoneMapping = [RKObjectMapping mappingForClass:[MyPhoneModel class]]; 
    [phoneMapping mapKeyPath:@"number" toAttribute:@"number"]; 
    [phoneMapping mapKeyPath:@"tag" toAttribute:@"tag"]; 

    RKObjectMapping *contactMapping = [RKObjectMapping mappingForClass:[MyContactModel class]]; 
    [contactMapping mapKeyPath:@"name" toAttribute:@"name"]; 
    [contactMapping mapKeyPath:@"phoneList" toRelationship:@"phoneList" withMapping:phoneMapping]; 

    NSError *error = nil; 
    NSString *json = [[RKObjectSerializer serializerWithObject:contact mapping:contactMapping] serializedObjectForMIMEType:RKMIMETypeJSON error:&error]; 
    return json; 
} 

但是,當我把這種方法,它與錯誤而失敗。 錯誤域= JKErrorDomain代碼= -1「無法序列化對象類MyPhoneModel」。 UserInfo = 0x898c400 {NSLocalizedDescription =無法序列化對象類MyPhoneModel。

那麼,如何解決這個問題呢?

回答

1

我發現這個鏈接: Examples of using

在每一個例子,我能找到的映射與[NSDictionary的類]或[的NSMutableDictionary類]

所以,也許這樣做:

RKObjectMapping* phoneMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class] ]; 
[phoneMapping mapAttributes:@"number", @"tag", nil]; 

RKObjectMapping *contactMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; 
[contactMapping mapKeyPath:@"name" toAttribute:@"name"]; 
[contactMapping mapKeyPath:@"phoneList" toRelationship:@"phoneList" withMapping:phoneMapping]; 

你想要這個序列化的字符串與RKClient一起使用嗎?

+0

謝謝,這就是我想要的! – wjldxt 2011-12-29 06:36:38