iphone - RestKit 映射嵌套字典中的值

标签 iphone ios json restkit

我收到这样的 JSON 响应

{
    "id" : 12345
    "course_name" : "history",
    "teacher" : "joy",
    "region" : {
                   "code" : "Al",
                   "name" : "Alabama"
               }
}

我在 coredata 中有一个类(class)实体,在代码中有一个相应的模型作为“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。 我不知道哪里出了问题。是否有可能得到这样的值。

最佳答案

对于 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"];

关于iphone - RestKit 映射嵌套字典中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16395925/

相关文章:

iphone - 后台模式下的iOS区域监控

ios - WKInterface 按钮不更改标题

javascript - Vue2 : JSON object using emit not working?

javascript - 使用 WebAPI Controller 序列化复杂的 json 对象

javascript - 使用 javascript/jquery 检测移动浏览器的最佳方法?

iphone - 为 iPhone 编译 FreeType?

iphone - 解析同名元素?

ios - UITextField 没有圆边

ios - CollectionView 默认项目选择

javascript - Meteor 将 JSON 导入集合