2013-07-01 55 views
0

我使用Restkit 0.20.x來映射對象從JSON像如何通過RestKit 0.20.x與結構複雜JSON

{ 
    "d":{ 
     "results":[ 
      { 
       "Web":[ 
        "key1":"value1", 
        "key2":"value2" 
       ], 
       "Image":[ 
        "key1":"value1", 
        "key2":"value2" 
       ], 
      }, 
     ], 
    }, 
} 

我的主要目的是管理「網絡」和「圖片」鍵映射對象。 我試圖映射對象,但卡在「結果」鍵(鍵「結果」的值是隻有一個元素作爲字典的數組)。 如何使用RestKit在我的情況下,映射對象?

我無法實現:

WFSD.h

@interface WFSD : NSObject 
@property (nonatomic, strong) WFSResults *results; 
@end 

WFSResults.h

@interface WFSResults : NSObject 
@property (nonatomic, strong) WFSResult *result; 
@end 

WFSResult.h

@interface WFSResult : NSObject 
@property (nonatomic, strong) WFSWeb *web; 
@property (nonatomic, strong) WFSImage *image; 
@end 

MyController.m

RKObjectMapping* dMapping = [RKObjectMapping mappingForClass:[WFSD class]]; 
RKObjectMapping* resultsMapping = [RKObjectMapping mappingForClass:[WFSResults class]]; 

RKRelationshipMapping* rsMapping1 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"results" toKeyPath:@"results" withMapping:resultsMapping]; 
[dMapping addPropertyMapping:rsMapping1]; 

RKObjectMapping* resultMapping = [RKObjectMapping mappingForClass:[WFSResult class]]; 
[resultsMapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:nil toKeyPath:@"result" withMapping:resultMapping]]; 

RKRelationshipMapping* rsMapping2 = [RKRelationshipMapping relationshipMappingFromKeyPath:@"Image" toKeyPath:@"Image" withMapping:imageMapping]; 
[resultMapping addPropertyMapping:rsMapping2]; 

RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor  responseDescriptorWithMapping:dMapping 
                         pathPattern:nil 
                          keyPath:@"d" 
                         statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]; 
+0

那你嘗試,以及如何你想存儲數據?顯示你的映射和數據結構。 – Wain

+0

我編輯了我的失敗工具。你有什麼建議嗎 ? –

回答

2

看看從你的模型類刪除WFSResults。實際上它只是一個WFSResult對象列表,所以你應該看看它建模爲:

@interface WFSD : NSObject 
@property (nonatomic, strong) NSArray *results; 
@end 

您還需要看看WFSResult,因爲在JSON WebImage也是數組。所以,我希望看到:

@interface WFSResult : NSObject 
@property (nonatomic, strong) NSArray *web; 
@property (nonatomic, strong) NSArray *image; 
@end 

這樣RestKit可以創建映射過程中的對象,然後它有一個數組存儲對象的列表。

+0

謝謝Wain,它像一個魅力。 –

+0

好東西,歡迎來到堆棧溢出:-)請接受解決問題並提高答案的答案。 – Wain

+1

能否請你告訴如何設置映射對象的嵌套數組?例如。在上面的例子中'web'是'Web'對象的'NSArray'。而'Web'又是具有一些屬性的對象。我如何訪問這些Web屬性?如果我做'Web * web = [web objectAtIndex:0]'然後'web.key1',我得到null。我怎樣才能做到這一點? – MainstreamDeveloper00