2012-09-23 38 views
0

我一直在使用RestKit,但一些API已經在最新版本中發生了變化,我不再能夠解析簡單的JSON。使用RestKit解析JSON

這裏的有效載荷我:

{ 
    "result":true, 
    "items":[ 
     { 
     "id":"1", 
     "receiver":"11011101" 
     }, 
     { 
     "id":"2", 
     "receiver":"11011101" 
     } 
    ] 
} 

我如何解析「項目」字典爲對象的會話實例的內容我已經創建了?

使用下面的代碼不起作用(對象不會映射):

RKObjectMapping* conversationMapping = [RKObjectMapping mappingForClass:[Conversation class]]; 
[conversationMapping mapKeyPath:@"id" toAttribute:@"id"]; 
[conversationMapping mapKeyPath:@"receiver" toAttribute:@"receiver"]; 

[[RKObjectManager sharedManager].mappingProvider setMapping:conversationMapping forKeyPath:@"items"]; 
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/getConversations" delegate:self]; 

會話班

@interface Conversation : NSObject { 
    NSString *id; 
    NSString *receiver; } 

+ (void)objectMapping; 

@property (nonatomic, strong) NSString *id; @property (nonatomic, strong) NSString *receiver; 

@end 

@implementation Conversation 
@synthesize id; 
@synthesize receiver; 


+ (void)objectMapping { 
    RKObjectMapping* conversationMapping = [RKObjectMapping mappingForClass:[Conversation class]]; 
    [conversationMapping mapKeyPath:@"id" toAttribute:@"id"]; 
    [conversationMapping mapKeyPath:@"receiver" toAttribute:@"receiver"]; 

    [[RKObjectManager sharedManager].mappingProvider setMapping:conversationMapping forKeyPath:@"items"]; 
} 

@end 
+0

顯示你的'Conversation'類 – wattson12

+2

也許你應該直接使用jsonkit。 – Janub

回答

0

我解決了這個問題。這與RestKit完全沒有關係。在修復該對象映射工作正常之後,從服務器返回的響應的內容類型未設置爲JSON。

0

如何定義你的根對象(即持有「結果」的人;你的對話「項目」)?這應該是這個樣子:

@interface MyResponse

@屬性(非原子,強)的NSArray *物品; @property(nonatomic,assign)BOOL結果;

以及適當的映射。