如何在iOS中解析JSON数据

时间:2014-06-01 10:08:41

标签: ios json

我收到服务器的回复格式

{updated_at: 12345555 dates:
    [{"start_date": "2014-03-02", "end_date": "2014-03-02"},
     {"start_date": "2014-04-02", "end_date": "2014-04-02"},
     {"start_date": "2014-05-02", "end_date": "2014-05-02"}]}

我想解析这些信息并将其添加到2个NSmutableArrays中,我不明白该怎么做

我试过这个

NSMutableArray *startDate = [NSMutableArray array];
NSMutableArray *endDate = [NSMutableArray array];

[dictionaries enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
    [startDate addObject:[obj valueForKeyPath:@"start_date"]];
    [endDate addObject:[obj valueForKeyPath:@"end_date"]];

}];

但我得错误说密钥无效。我不明白我哪里出错了。

3 个答案:

答案 0 :(得分:3)

{}:表示NSDictionary

[]:表示NSArray

 NSArray *dates = [yourJsonData objectForKey:@"dates"];
 for(NSDictionary *data in dates){
    [startDate addObject: [data objectForKey: start_date];
    [endDate addObject: [data objectForKey: end_date];
 }

答案 1 :(得分:1)

您在NSDictionary时尝试枚举NSArray。您的dictionaries对象应为NSArray类型,然后

for(int i = 0; i<dictionaries.count; i++)
{
  [startDate addObject:[obj valueForKeyPath:@"start_date"]];
  [endDate addObject:[obj valueForKeyPath:@"end_date"]];
}

答案 2 :(得分:0)

如果显示的数据是您获得的数据,那么它是无效的JSON。

在JSON中,需要引用键,键/值对之间需要有逗号:

{"updated_at": 12345555 dates:
    [{"start_date": "2014-03-02", "end_date": "2014-03-02"},
     {"start_date": "2014-04-02", "end_date": "2014-04-02"},
     {"start_date": "2014-05-02", "end_date": "2014-05-02"}]}