Restkit映射嵌套数组

6

我有一个关于映射嵌套数组的问题。在https://github.com/RestKit/RestKit/blob/master/Docs/Object%20Mapping.md上,有一个映射嵌套对象的示例。

但是如果嵌套对象是一个对象数组,该怎么办?例如JSON如下:

{ "articles": [
    { "title": "RestKit Object Mapping Intro",
      "body": "This article details how to use RestKit object mapping...",
      "author": [{
          "name": "Blake Watters",
          "email": "blake@restkit.org"
      },
      {
          "name": "abc",
          "email": "emailaddress"
      }]
      "publication_date": "7/4/2011"
    }]
}

我的类应该是什么样子,才能获取作者数组? 以下是示例代码:
@interface Author : NSObject
    @property (nonatomic, retain) NSString* name;
    @property (nonatomic, retain) NSString* email;
@end



@interface Article : NSObject
    @property (nonatomic, retain) NSString* title;
    @property (nonatomic, retain) NSString* body;
    @property (nonatomic, retain) Author* author; // should be an array of Author-Objects
    @property (nonatomic, retain) NSDate*   publicationDate;
@end

我该如何告诉Restkit,有一个作者数组,并且如果我将文章中的作者属性更改为NSArray类,Restkit如何知道在这个NSArray中应该包含哪些作者对象...??

我正在使用RKObjectMapping将对象从JSON映射到Objective-C,反之亦然。

4个回答

8

你需要确保按照正确的方式设置变量类型:

@interface Article : NSObject
    @property (nonatomic, retain) NSString* title;
    @property (nonatomic, retain) NSString* body;
    @property (nonatomic, retain) NSSet* authors;
    @property (nonatomic, retain) NSDate*   publicationDate;
@end

这段代码可能可以用NSArray来声明,但我个人更喜欢使用将RestKit与CoreData模型配合使用,这种情况下关系应该是NSSet。

此外,您还需要设置映射:

[articleMapping mapKeyPath:@"author" toRelationship:@"authors" withMapping:authorMapping];

3
分离它有所帮助。
@interface Author : NSObject
    @property (nonatomic, retain) NSString* name;
    @property (nonatomic, retain) NSString* email;
@end



@interface Article : NSObject
    @property (nonatomic, retain) NSString* title;
    @property (nonatomic, retain) NSString* body;
    @property (nonatomic, retain) NSArray* author; 
    @property (nonatomic, retain) NSDate*   publicationDate;
@end


//create the article mapping
RKObjectMapping *articleMapping = [RKObjectMapping mappingForClass:[Article class]];
//add rest of mappings here
[articleMapping addAttributeMappingsFromDictionary:@{
                                                  @"title":@"title"
} 

//create the author mapping
RKObjectMapping *authorMapping = [RKObjectMapping mappingForClass:[Author class]];
//add rest of mappings here
[authorMapping addAttributeMappingsFromDictionary:@{
                                                  @"name":@"name"
} 

//link mapping with a relationship
RKRelationshipMapping *rel = [RKRelationshipMapping relationshipMappingFromKeyPath:@"authors" toKeyPath:@"author" withMapping:authorMapping];

//add relationship mapping to article
[articleMapping addPropertyMapping:rel];

0

0

将整个响应字符串视为可变字典,然后将作者值分配给可变数组。


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