实现MTLModel显示错误解析json字典

时间:2015-04-11 00:11:04

标签: ios objective-c json github-mantle

错误消息如下:

 *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<Channel 0x7fb34b5d1420> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key user.'

以下是代码:

NSDictionary *json = @{@"u1" : @{@"handle" : @"h1", @"authToken" : @"123"}};
NSError *e = nil;
Channel *c = [[Channel alloc] initWithDictionary:json error:&e];
NSLog(@"channel.u1.handle: %@", c.u1.handle);

Channel.m

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
        return @{
            @"u1" : @"u1"
        };
}

+ (NSValueTransformer *)u1Transformer {
    return [MTLJSONAdapter dictionaryTransformerWithModelClass:[User class]];
}

User.m

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
        return @{
            @"handle" : @"handle",
            @"authToken" : @"token"
        };
}

使用Mantle, iOS json parsing framework

如何将JSON解析为可可对象?

1 个答案:

答案 0 :(得分:0)

一个简单的问题:您使用的Mantle版本是什么?

此行不会使用Mantle 1.5.4进行编译。

return [MTLJSONAdapter dictionaryTransformerWithModelClass:[User class]];

要使其工作,您需要将其更改为

return [NSValueTransformer mtl_JSONDictionaryTransformerWithModelClass:[User class]];

此外,如果您想使用initWithDictionary:error:初始化Channel实例,则需要覆盖该方法,这是一个示例:

-(instancetype)initWithDictionary:(NSDictionary *)dictionaryValue 
                            error:(NSError *__autoreleasing *)error
{
    self = [super initWithDictionary:dictionaryValue error:error];
    if(self){
        self.u1 = [[User alloc] initWithDictionary:[dictionaryValue objectForKey:@"u1"] 
                                             error:error];
    }
    return self;
}

或者只使用modelOfClass:fromJSONDictionary:error:这是MTLJSONAdapter的静态方法。在您的情况下,您可能有这样的代码:

NSDictionary *json = @{@"u1" : @{@"handle" : @"h1", @"authToken" : @"123"}};
NSError *e = nil;
Channel *c = [MTLJSONAdapter modelOfClass:[Channel class] 
                       fromJSONDictionary:json 
                                    error:&e];

希望这会有所帮助:)