0

嗨,我已经实现了用于解析以下响应的代码,但它无法正常工作:

 NSString *req = [NSString stringWithFormat: @" My URL"];   
 NSDictionary *googleResponse = [[NSString stringWithContentsOfURL: [NSURL URLWithString: req] encoding: NSUTF8StringEncoding error: NULL] JSONValue];        
 NSDictionary *resultsDict = [googleResponse valueForKey:  @"eventtitle"];

解析以下响应的代码是什么?请给我解决方案。

{
  "AlansHarleyEvents": [
    {
      "id": "3",
      "eventtitle": "22nd Annual Pig Roast",
      "eventdate": "April 22nd 8am-5pm"
    },
    {
      "id": "4",
      "eventtitle": "Poker Run",
      "eventdate": "April 28th 8am at Shooters"
    },
    {
      "id": "5",
      "eventtitle": "Kickstands for kids",
      "eventdate": "May 12th 8am-5pm"
    },
    {
      "id": "6",
      "eventtitle": "Ride for the Cure",
      "eventdate": "May28th 8am Free Drinks!"
    },
    {
      "id": "7",
      "eventtitle": "Veterans Ride",
      "eventdate": "June 10th 9am @City Hall"
    },
    {
      "id": "8",
      "eventtitle": "Biker Beach Bash",
      "eventdate": "June 28th 8-5pm @ The Pier"
    },
    {
      "id": "10",
      "eventtitle": "22nd Annual Pig Roast",
      "eventdate": "April 22nd 8am-5pm"
    },
    {
      "id": "11",
      "eventtitle": "Poker Run",
      "eventdate": "April 28th 8am at Shooters Lounge"
    },
    {
      "id": "12",
      "eventtitle": "22nd Annual Pig Roast",
      "eventdate": "April 22nd 8am-5pm"
    },
    {
      "id": "13",
      "eventtitle": "Swamp Run",
      "eventdate": "April 22nd 8am-5pm"
    }
  ]
}
4

3 回答 3

1

NSJSONSerialization 类是仅适用于 iOS 5 及更高版本的本地类 http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html

对于任何 iPhone 操作系统版本意味着您可以使用 JSONKit: https ://github.com/johnezang/JSONKit

于 2012-05-18T07:16:01.483 回答
1

如果您resultsDict包含上述 JSON 响应,那么您可以将其解析为:

NSString *req = [NSString stringWithFormat: @" My URL"];
NSDictionary *googleResponse = [[NSString stringWithContentsOfURL: [NSURL URLWithString: req] encoding: NSUTF8StringEncoding error: NULL] JSONValue];
NSDictionary *resultsDict = [googleResponse valueForKey: @"eventtitle"];

NSMutableArray *resultArray = [resultsDict valueForKey:@"AlansHarleyEvents"]; 

for(int i = 0; i<[resultArray count]; i++)
{
    NSLog(@"%@",[[resultArray objectAtIndex:i] valueForKey:@"id"]) ;
    NSLog(@"%@",[[resultArray objectAtIndex:i] valueForKey:@"eventtitle"]) ;
    NSLog(@"%@",[[resultArray objectAtIndex:i] valueForKey:@"eventdate"]) ; 
}
于 2012-05-18T07:16:03.087 回答
1

Yu 可以在 IOS 5 中使用 NSJSONSerialization 对象

   NSDictionnary *jsonObject = [NSJSONSerialization JSONObjectWithData:resultsDict options:NSJSONReadingMutableContainers error:&error];
于 2012-05-18T07:23:02.433 回答