RestKit:从嵌套字典中映射值

4
我收到的 JSON 响应如下:
{
    "id" : 12345
    "course_name" : "history",
    "teacher" : "joy",
    "region" : {
                   "code" : "Al",
                   "name" : "Alabama"
               }
}

我在CoreData中有一个课程实体,对应的代码模型为“MKCourse”,这个实体是这样的:

MKCourse
  - id
  - courseName
  - teacher
  - regionCode
  - regionName

我正在像这样从MKCourse中的嵌套字典中设置值 -
mapping = [RKManagedObjectMapping mappingForClass:[self class] inManagedObjectStore:[[RKObjectManager sharedManager] objectStore]];
    mapping.setDefaultValueForMissingAttributes = YES;
    mapping.setNilForMissingRelationships = YES;

    [mapping mapKeyPathsToAttributes:
     @"id", [self modelIdAttribute],
     @"course_name", @"courseName",
     @"teacher", @"teacher",
     @"region.code", @"regionCode",
     @"region.name", @"regionName",
     nil];

但它总是将regionCode和regionName设为nil。我不知道出了什么问题。是否可能获取这样的值。
1个回答

2

如果是 RestKit 2.+ 版本,请添加以下代码:

[mapping addAttributeMappingFromKeyOfRepresentationToAttribute:@"region"];

尝试使用 addAttributeMappingsFromDictionary 方法

[mapping addAttributeMappingsFromDictionary:@{
    @"id", [self modelIdAttribute],
     @"course_name", @"courseName",
     @"teacher", @"teacher",
     @"region.code", @"regionCode",
     @"region.name", @"regionName"
}];

不确定RestKit 1.0。也许你可以尝试将它们分开:

[mapping mapKeyPath:@"id" toAttribute:[self modelIdAttribute]];
[mapping mapKeyPath:@"course_name" toAttribute:@"courseName"];
[mapping mapKeyPath:@"teacher" toAttribute:@"teacher"];
[mapping mapKeyPath:@"region.code" toAttribute:@"regionCode"];
[mapping mapKeyPath:@"region.name" toAttribute:@"regionName"];

感谢您的回答。不幸的是,这在Restkit的0.2版本中得到了支持,但我正在使用0.1版本。现在我没有改变我的代码以支持0.2版本的位置。有什么办法可以在不使用addAttributeMappingFromKeyOfRepresentationToAttribute的情况下实现它吗? - kmithi1
@Mithielsh不确定RestKit 1.0如何。尝试将它们分开(已更新答案)。 - Dmitry Khryukin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接