RestKit:serializedObjectForMIMEType失败并出现错误

时间:2011-12-28 06:06:24

标签: objective-c restkit

我正在尝试使用RestKit从我的自定义对象中获取JSON格式字符串。

这是我的代码:

@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;
}

但是当我调用此方法时,它失败并出现错误。 错误Domain = JKErrorDomain Code = -1“无法序列化对象类MyPhoneModel。” UserInfo = 0x898c400 {NSLocalizedDescription =无法序列化对象类MyPhoneModel。

那么,如何解决这个问题?

1 个答案:

答案 0 :(得分: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一起使用吗?