【问题标题】:How to parse this repsonse in restkit?如何在休息套件中解析此响应?
【发布时间】:2016-02-24 07:21:15
【问题描述】:

我完全困惑于在 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 都是零。在这种情况下如何进行正确的映射。

【问题讨论】:

  • 你试过什么代码?你在使用NSJSONSerialization 吗?它看起来很简单——一个字典,其中每个键都包含一个字典数组
  • @Paulw11 是的,可以使用 NSJSONSerialization 来完成。但我正在使用 RestKit 进行对象映射。
  • 好的,您能展示一下您使用该框架尝试过的内容吗?
  • 对究竟是什么感到困惑?

标签: ios objective-c restkit


【解决方案1】:

这个属性:

@property (nonatomic, strong) NSString *arrPersons;

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

@property (nonatomic, strong) NSMutableArray *arrPersons;

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

【讨论】:

  • 哦!那是我犯的一个愚蠢的错误。感谢您的帮助韦恩。现在工作正常
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-04
  • 2020-03-17
  • 2023-02-22
  • 1970-01-01
  • 2012-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多