2013-05-30 90 views
1

我具有以下JSON:RestKit映射多個類型的陣列

{ 
    "stream": [{ 
     "catalog": {} 
    }, { 
     "catalog": {} 
    }, { 
     "user": {} 
    }] 
} 

與以下映射規則:直到多個對象類型是在流中

[RKResponseDescriptor responseDescriptorWithMapping:catalogMapping 
             pathPattern:nil keyPath:@"stream.catalog" 
             statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]]; 

[RKResponseDescriptor responseDescriptorWithMapping:userMapping 
             pathPattern:nil keyPath:@"stream.user" 
             statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]]; 

映射工作正常。當流包含多個對象,說用戶和目錄restkit失敗此斷言:

NSCAssert([representation isKindOfClass:[NSDictionary class]], @"Expected a dictionary representation"); 

有沒有一種方法映射結構?

+0

所以有時候「流」是JSON,有時一本字典這是一個數組? – Wain

+0

它始終是一個字典數組。 – Ivan

+0

在這種情況下,流是一個數組,而不是字典?意思'流'是一個數組? –

回答

3

我有一個豪華請求一個API的變化,所以我們搬到

{ 
    "stream": [{ 
     "type": "catalog", 
     "other": "fields" 
    }, { 
     "type": "catalog" 
     "other": "fields" 
    }, { 
     "type": "user" 
     "other": "fields" 
    }] 
} 

的,現在我使用動態映射:

RKDynamicMapping* dynamicMapping = [RKDynamicMapping new]; 
    [dynamicMapping setObjectMappingForRepresentationBlock:^RKObjectMapping *(id representation) { 
     if ([[representation objectForKey:@"type"] isEqualToString:@"catalog"]) { 
      return catalogMapping; 
     } else if ([[representation objectForKey:@"type"] isEqualToString:@"user"]) { 
      return userMapping; 
     } 
//  ... 
    }]; 


    [manager addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:dynamicMapping 
                      pathPattern:nil keyPath:@"stream" 
                      statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]];