简体   繁体   English

如何在iOS中解析JSON数据

[英]How to parse JSON data in iOS

I am getting response from server in this format 我正在以这种格式从服务器获得响应

{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"}]}

I want to parse this information and add it to 2 NSmutableArrays, I am not understanding how to do this 我想解析此信息并将其添加到2个NSmutableArrays中,我不了解如何执行此操作

I tried this 我试过了

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"]];

}];

But I get error saying that the key is invalid. 但是我收到错误消息,说密钥无效。 I am not understanding where I am going wrong. 我不明白我要去哪里错了。

{} : means NSDictionary {} :表示NSDictionary

[] : means NSArray [] :表示NSArray

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

You're trying to enumerate NSDictionary while you have NSArray . 您尝试在拥有NSArray枚举NSDictionary Your dictionaries object should be of type NSArray then 您的dictionaries对象应为NSArray类型,然后

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

If the shown data is what you get, then it's not valid JSON. 如果显示的数据是您得到的,则它不是有效的JSON。

In JSON, the keys need to be quoted and there needs to be a comma between key/value pairs: 在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"}]}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM