我有一个干净的RESTful API,它为我提供了以下端点
/厂商
/供应商/:ID /国家
/ vendors /:id / countries /:id / cities
对于Objective-C和RESTkit,我缺乏经验。就在我正在寻找一种方法将服务器端对象映射到客户端的3个类:供应商,国家,城市。
所以我希望每个班级的宣言
a)定义可以获取JSON对象的端点
b)定义从供应商到国家以及从国家到城市的1:n关系。
在这样做之后,我希望能够做类似的事[伪代码]:
vendors = Vendors.all //retrieve all vendors and construct objects
countries = vendors[0].countries //retrieve all countries of the first vendor
city = countries.last.cities //retrieve the cities of the last countries
不幸的是我在RESTkit中看不到类似的东西。为了能够在对象之间创建关系,API必须提供嵌套资源!例如,对countries端点的调用必须直接在JSON国家/地区内提供相关的供应商对象?!?
这是我根本不懂的东西。在那种情况下,我会使用各种遗留协议,而不必使用RESTful API。
我忽略了什么吗?任何人都可以帮助解决这个问题,或者提供一个资源解释RESTkit的链接比文档更详细吗?
答案 0 :(得分:0)
RestKit文档有一个部分:没有KVC的映射,涵盖了这一点。
RKPathMatcher:路径匹配器评估要生成的URL模式 与诸如'/ articles /:articleID'之类的模式匹配 匹配'/ articles / 1234'或'/ articles / some-great-article'。
https://github.com/RestKit/RestKit/wiki/Object-mapping#mapping-without-kvc
注意:我还没有尝试过这个,但是最新版本的RestKit(0.20.0)似乎更新了文档
答案 1 :(得分:-2)
回答你的问题,是的,你可以使用RestKit定义关系,JSON表示需要嵌套,前瞻以查看这个例子,以及如何将它映射到你的对象上。
您必须按照以下步骤操作:
使用从API获得的属性创建对象。
您需要设置与每个对象关联的映射 以及从API获得的JSON / XML。
来自Object Mapping Documentation:
需要解析以下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"
},
"publication_date": "7/4/2011"
}]
}
在Objective-c中定义对象:
//author.h
@interface Author : NSObject
@property (nonatomic, retain) NSString* name;
@property (nonatomic, retain) NSString* email;
@end
//article.h
@interface Article : NSObject
@property (nonatomic, retain) NSString* title;
@property (nonatomic, retain) NSString* body;
@property (nonatomic, retain) Author* author; //Here we use the author object!
@property (nonatomic, retain) NSDate* publicationDate;
@end
设置映射:
// Create our new Author mapping
RKObjectMapping* authorMapping = [RKObjectMapping mappingForClass:[Author class]];
// NOTE: When your source and destination key paths are symmetrical, you can use mapAttributes: as a shortcut
[authorMapping mapAttributes:@"name", @"email", nil];
// Now configure the Article mapping
RKObjectMapping* articleMapping = [RKObjectMapping mappingForClass:[Article class]];
[articleMapping mapKeyPath:@"title" toAttribute:@"title"];
[articleMapping mapKeyPath:@"body" toAttribute:@"body"];
[articleMapping mapKeyPath:@"author" toAttribute:@"author"];
[articleMapping mapKeyPath:@"publication_date" toAttribute:@"publicationDate"];
// Define the relationship mapping
[articleMapping mapKeyPath:@"author" toRelationship:@"author" withMapping:authorMapping];
[[RKObjectManager sharedManager].mappingProvider setMapping:articleMapping forKeyPath:@"articles"];
我希望这对你有用!