Restkit映射嵌套数组
我得到了一个映射嵌套数组的问题。 在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,那是一个作者数组,以及如果我将Article中的作者Attribute属性更改为NSArray,Restkit如何知道,在此NSArray中应该是Author-Objects ...?
我正在使用RKObjectMapping将对象从JSON映射到Objective-c,反之亦然。
您需要确保相应地设置var类型:
@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];
将其分割出来有所帮助。
@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];
整个respnse字符串将其作为nsmutable字典,然后将作者值分配给namutable数组。
链接地址: http://www.djcxy.com/p/49189.html上一篇: Restkit Mapping Nested Array
下一篇: Load a simple array