2012-01-31 30 views
4

HOWTO请求嵌套的资源我有一个干净的RESTful API,它为我提供了以下端点使用RESTkit的Objective-C的

/供应商
/供应商/:ID /国家
/供应商/:ID /国家/:编号/城市

对于Objective-C和RESTkit,我缺乏经验。就在此刻,我正在寻找一种方法将服务器端对象映射到客户端的3个类:供应商,国家,城市。

所以我期待每类

一)定义了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必须提供嵌套的资源!例如,对国家端点的调用将不得不直接在国家/地区内提供相关供应商对象。

这是我根本不理解的东西。在这种情况下,我会使用各种传统协议,而不必使用RESTful API。

我忽略了什么吗?任何人都可以在这个主题上提供帮助,或者提供一个链接到一个资源解释RESTkit比文档更详细吗?

回答

-2

回答您的问题,是的,您可以使用RestKit定义关系,并且需要嵌套JSON表示,向前阅读以查看此示例以及如何将其映射到您的对象上。

你必须遵循此步骤:

  1. 使用您从API获得的属性创建对象。

  2. 您需要设置与您的每个对象 以及从API获取的JSON/XML相关联的映射。

  3. 如果对象的属性是另一个对象,则定义对象之间的映射。

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": "[email protected]" 
     }, 
     "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"]; 

我希望这可以对你有用!

+1

问题是关于嵌套资源的提供,而不是映射。 – 2012-07-02 15:30:39

0

RestKit文档包含一个部分:不包含KVC的映射,其中涵盖了此部分。

RKPathMatcher:路径匹配评估URL模式以产生 比赛用的图案,如 '/物品/:条款ArticleID',这将针对 '/物品/ 1234' 或“/物品/一些-great-匹配文章'。

https://github.com/RestKit/RestKit/wiki/Object-mapping#mapping-without-kvc

注:我没有尝试这样做,但是这场文档似乎是RestKit的最新版本进行更新(0.20.0)