我有一个映射嵌套数组的问题。在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中应该是Author-Objects ......?
我正在使用RKObjectMapping将对象从JSON映射到Objective-c,反之亦然。
答案 0 :(得分:7)
您需要确保相应地设置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];
答案 1 :(得分: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];
答案 2 :(得分:0)
整个响应字符串将其作为nsmutable字典,然后将作者值分配给可变数组..
答案 3 :(得分:0)
您需要做的是使用NSSet属性来保存嵌套数组。这是一本完整的指南,可以帮助您做到https://medium.com/ios-os-x-development/restkit-tutorial-how-to-fetch-data-from-an-api-into-core-data-9326af750e10。