如何在iOS应用程序上解析JSon数据

时间:2014-01-23 03:36:42

标签: ios objective-c json

{"code":200,"msg":"","type":"DEFAULT",
"data{"thumbsId":209834,"thumbsKind":"UP","fbObjectId":null,"canPostFB":true,"thumbsupCnt":292,"episodeId":2491},
"errorDetails":null}

我希望得到thumbskind数据值。我的代码如下:

@property(nonatomic, assign) NSInteger code;
@property(nonatomic, copy) NSString *msg;
@property(nonatomic, copy) NSString *type;
@property(nonatomic, copy) NSString *details; 
@property(nonatomic, copy) NSDictionary *data;


 NSDictionary *obj = (NSDictionary *)sender;

self.code = [[obj objectForKey:@"code"] intValue];
self.msg = [obj valueForKeyPath:@"msg"];
self.type = [obj valueForKeyPath:@"type"];
self.data = [obj valueForKeyPath:@"data"];
self.details = [obj valueForKeyPath:@"errorDetails"];

我可以获得codetypemsg等等。

但我无法获得data的值。 如何获取thumbsIdthumbsKindthumbsupCnt

等值

4 个答案:

答案 0 :(得分:0)

数据是字典中的字典,所以试试这个

@property(nonatomic, copy) NSString * thumbsId;
@property(nonatomic, copy) NSString * thumbsKind;  
. 
. 
.

NSDictionary *obj = (NSDictionary *)sender;
NSDictionary *dataDict = (NSDictionary *)  [obj objectForKey:@"data"]


self. thumbsKind = [dataDict valueForKeyPath:@"thumbsKind"]; 
self.thumbsId = [dataDict valueForKeyPath:@"thumbsId"];
. 
.

答案 1 :(得分:0)

NSInteger thumbsId = [[self.data objectForKey:@"thumbsId"] intValue];

NSString *thumbsKind = [self.data objectForKey:@"thumbsKind"];

......

答案 2 :(得分:0)

您的数据采用错误的Json格式

应该是这样的:

"data:{"thumbsId":209834,"thumbsKind":"UP","fbObjectId":null,"canPostFB":true,"thumbsupCnt":292,"episodeId":2491},

而不是

"data{"thumbsId":209834,"thumbsKind":"UP","fbObjectId":null,"canPostFB":true,"thumbsupCnt":292,"episodeId":2491},

然后尝试

NSDictionary *dataDict = (NSDictionary *)  [obj objectForKey:@"data"]
self. thumbsKind = [dataDict valueForKeyPath:@"thumbsKind"]; 
self.thumbsId = [dataDict valueForKeyPath:@"thumbsId"];

答案 3 :(得分:0)

你可以这样做

NSInteger thumbsId = [[obj valueForKeyPath:@"data.thumbsId"] intValue];

使用
可以减少编码痛苦并节省时间 JSON Accelerator