2012-01-31 65 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)