【问题标题】:RestKit Map values from nested dictionary嵌套字典中的 RestKit 映射值
【发布时间】:2013-04-30 01:00:25
【问题描述】:

我收到这样的 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。 我不知道出了什么问题。是否有可能得到这样的值。

【问题讨论】:

    标签: iphone ios json restkit


    【解决方案1】:

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

    【讨论】:

    • 感谢您的回答。不幸的是,0.2 版本的 Restkit 支持这一点,但我使用的是 0.1 版本。现在我无法更改我的代码以支持 0.2 版本。关于我们如何在没有 addAttributeMappingFromKeyOfRepresentationToAttribute 的情况下实现它的任何想法?
    • @Mithielsh 不确定 RestKit 1.0。尝试将它们分开(已更新答案)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 2014-06-30
    • 2015-11-07
    • 2014-09-01
    相关资源
    最近更新 更多