2

错误消息如下所示:

 *** 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 解析框架

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

4

1 回答 1

0

One quick question: what version of Mantle are you using?

This line does not compile with Mantle 1.5.4.

return [MTLJSONAdapter dictionaryTransformerWithModelClass:[User class]];

To make this work, you'll need to change it to

return [NSValueTransformer mtl_JSONDictionaryTransformerWithModelClass:[User class]];

Also, if you want to use initWithDictionary:error: to initialise a Channel instance, you'll need to override that method, here's an example:

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

Or simply use modelOfClass:fromJSONDictionary:error: which is a static method of MTLJSONAdapter. In your case, you may have code like this:

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

Hope this helps :)

于 2015-04-29T11:37:01.500 回答