2012-05-18 208 views
0

您好我已經實現代碼解析如下回應如下,但它不能正常工作:解析Json解析的代碼如何?

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

回答

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"]) ; 
} 
+0

爲什麼不能投票??? – Maulik

+0

我認爲downvote是由'resultsDict'沒有鍵/值'AlansHarleyEvents'這個事實引起的。 – Mat

+0

@maulik:當我使用你的代碼時,它給了我NSDictionary *谷歌響應的空值* [[NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL] JSONValue]; – user1402718

1

Yu可以使用NSJSONSerialization對象與IOS 5

NSDictionnary *jsonObject = [NSJSONSerialization JSONObjectWithData:resultsDict options:NSJSONReadingMutableContainers error:&error];