2014-03-28 92 views
3

我正在努力尋找一種將一些JSON映射到RestKit的方法。這就是我要找一個例子:RestKit:使用數組的動態嵌套屬性

 "results":{ 
      "Test1":[ 
       { 
       "id":1, 
       "name":"Test 1 here.", 
       "language":"English", 
       "type: "Test1" 
       } 
      ], 
      "Test2":[ 
       { 
       "id":3, 
       "name":"Another test 2", 
       "language":"English", 
       "type":"Test2" 
       }, 
       { 
       "id":8, 
       "name":"More test 2", 
       "language":"English", 
       "type":"Test2" 
       }, 
       { 
       "id":49, 
       "name":"foo", 
       "language":"English", 
       "type":"Test2" 
       } 
      ] 
     } 

理想情況下,JSON將不包括「類型」爲重點的額外多餘的一層,但生活就是這樣。

我想RestKit返回下類型的「成果」 4個對象:

@interface Test : NSObject 

@property (nonatomic, copy) NSNumber *testId; 
@property (nonatomic, copy) NSString *testName; 
@property (nonatomic, copy) NSString *testLanguage; 
@property (nonatomic, copy) NSString *testType; 

我試過,例如映射的不同組合:

RKObjectMapping *testMapping = [RKObjectMapping mappingForClass:[Test class]]; 
testMapping.forceCollectionMapping = YES; 
[testMapping addAttributeMappingFromKeyOfRepresentationToAttribute:@"testType"]; 
[testMapping addAttributeMappingsFromDictionary:@{ 
                 @"(testType).id": @"testId", 
                 @"(testType).name": @"testName", 
                 @"(testType).language": @"testLanguage", 
                 }]; 

但它仍然失敗,因爲它不是「類型」JSON鍵下的單個對象 - 它是一個Test對象的數組。

有沒有辦法在RestKit中表示這種映射?或者,如果沒有,能夠覆蓋一些回調函數,所以我可以使它工作?不幸的是,我無法更改來自服務器的JSON數據

+0

是關鍵(的Test1,Test2的,...)任意的,或者是有一組已知的選擇? – Wain

+0

不幸的是,它們是未知的。並且可以有任意數量的它們。 – ClemsonJeeper

回答

2

我想說你最好的選擇是創建一個響應描述符,其關鍵路徑爲@"results"dynamic mapping。該映射將返回一個映射,映射到一個NSDictionary並且定義了許多關係。這本詞典只是一個容器,用於促進其他映射(關係)。

的關係由迭代提供給動態映射和創建每個迭代一個關係的表示的鍵,用testMapping創建的,但沒有addAttributeMappingFromKeyOfRepresentationToAttribute如現在可以使用直接屬性訪問(和內type屬性) 。

使用setObjectMappingForRepresentationBlock:,您的塊提供了representation,在您的情況下,它是反序列化的JSON的NSDictionary。在塊內部,您可以像往常一樣創建映射,但基於字典中鍵的內容。


RKObjectMapping *testMapping = [RKObjectMapping mappingForClass:[Test class]]; 
[testMapping addAttributeMappingsFromDictionary:@{ @"id": @"testId", @"name": @"testName" }]; 

[dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) { 
    RKObjectMapping *testListMapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]]; 
    for (NSString *key in representation) { 
     [testListMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeypath:key toKeyPath:key withMapping:testMapping]; 
    } 

    return testListMapping; 
}]; 
+0

感謝您對此的迴應。不過,我不太清楚我是否跟着你。我對RestKit比較新,所以我不確定如何實現你所說的內容 - 有沒有什麼可以推薦作爲這樣的例子看的? – ClemsonJeeper

+0

我已經添加了一些信息。這種映射AFAIK沒有指南。嘗試一下,如果你有問題,請展示你的代碼。 – Wain

+0

啊,我現在明白了。那是我錯過的部分。謝謝! – ClemsonJeeper