如何在restkit中解析这个repsonse?

时间:2016-02-24 07:21:15

标签: ios objective-c restkit

我很困惑在restkit中解析这种响应。我正在使用这个link,但我无法理解如何解析这个回复。任何帮助都将不胜感激。

“groups”: {
      "group1": [
        {        
         "email": "blake@restkit.org",        
         "favorite_animal": "Monkey"    
        },
        {        
         "email": "slake@restkit.org",        
         "favorite_animal": "Donkey"    
        }
      ],    
      "group2": [
        {
         "email": "sarah@restkit.org",   
         "favorite_animal": "Cat"
        },
        {
         "email": "varah@restkit.org",   
         "favorite_animal": "Cow"
        }
      ]
    }

我在使用下面的映射。

@interface GroupResponse : NSObject

@property (nonatomic, strong) NSArray *Groups;

+ (RKObjectMapping *)mapping;

@end

@implementation GroupResponse

+ (RKObjectMapping *)mapping {

    RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[self class]];
    [objectMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@“groups” toKeyPath:@“Groups” withMapping:[GroupData mapping]]];

    return objectMapping;
}
@end



@interface GroupData : NSObject

@property (nonatomic, strong) NSString *groupName;
@property (nonatomic, strong) NSString *arrPersons;

+ (RKObjectMapping *)mapping;

@end

@implementation GroupData

+ (RKObjectMapping *)mapping {

    RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[self class]];

    objectMapping.forceCollectionMapping = YES;
    [objectMapping addAttributeMappingFromKeyOfRepresentationToAttribute:@"groupName"];

    [objectMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@“(groupName)” toKeyPath:@"arrPersons" withMapping:[Person mapping]]];

    return objectMapping;
}

@end


@interface Person : NSObject

@property (nonatomic, strong) NSString *email;
@property (nonatomic, strong) NSString *favAnimal;

+ (RKObjectMapping *) mapping;
@end

@implementation Person

+ (RKObjectMapping *)mapping {

    RKObjectMapping *objectMapping = [RKObjectMapping mappingForClass:[self class]];

    [objectMapping addAttributeMappingsFromDictionary:@{@"email" : @"email",
                                                        @"favorite_animal" : @"favAnimal"}];

    return objectMapping;
}

@end

每次 arrPersons 都是零。在这种情况下如何进行正确的映射。

1 个答案:

答案 0 :(得分:1)

此属性:

@property (nonatomic, strong) NSString *arrPersons;

实际上应该是一个可变数组,而不是字符串类型:

@property (nonatomic, strong) NSMutableArray *arrPersons;

因为嵌套的JSON数组无法转换为字符串,并且您的映射表明它应该被处理为Person个对象的数组。