2012-02-06 174 views
2

我的代码:JSON解析问题

NSString *jsonString; 

jsonString = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 

// Create a dictionary from the JSON string 
NSDictionary *results = [jsonString JSONValue]; 

NSLog(@"%@",jsonString); 
// Build an array from the dictionary for easy access to each entry 
NSArray *places = [results objectForKey:@"description"]; 

我没有得到结果我想要的。 当我调试代码时,我得到2个键/值对的NSArray地方的对象。

+0

链路:HTTPS:?//maps.googleapis.com/maps/api/place/autocomplete/json输入=肖拉普尔&传感器=真键= AIzaSyC0K5UhV_BWmXhncIZEnbh-WG2RVQVgfdY – anjum 2012-02-06 12:20:13

回答

1

这是正确的,你有2个键/值对。前两个键完好无损是“预测”和“状态”。所以你必须首先提取预测(它是一个数组):


NSArray *predictions = [results objectForKey:@"predictions"]; 

然后迭代它;还注意到,“说明”是一个字符串,让你必须使用“”分隔它拆分地方:


for(NSDictionary *aPrediction in predictions) { 
    NSString *description = [aPrediction objectForKey:@"description"]; 
    NSArray *placesInDescription = [description componentsSeparatedByString:@","]; 
} 
+0

我仍然在为NSArray预测获取0个对象 – anjum 2012-02-06 12:53:32

+0

“预测”名称中存在错字 – viggio24 2012-02-06 14:18:12

+0

对不起,我没有得到你想要解释的内容。 – anjum 2012-02-06 14:20:32

0

也许你应该使用:

NSArray *places = [results valueForKey:@"predictions"]; 
+0

0对象的地点。 – anjum 2012-02-06 12:59:48

+0

使用:NSArray * places = [results valueForKey:@“predictions”];而不是“objectForKey”。 – CarlJ 2012-02-06 13:18:30

+0

仍然相同。 – anjum 2012-02-06 13:23:44

0

工作对我来说没有用JSON包的任何问题! JSON文件的

NSString *jsonString; 

     NSData *responseData = [NSData dataWithContentsOfURL: [NSURL URLWithString:@"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=solapur&sensor=true&key=AIzaSyC0K5UhV_BWmXhncIZEnbh-WG2RVQVgfdY"]]; 

     jsonString = [[NSMutableString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]; 

     // Create a dictionary from the JSON string 
     NSDictionary *results = [jsonString objectFromJSONString]; 

     // Build an array from the dictionary for easy access to each entry 
     NSArray *places = [results valueForKey:@"predictions"]; 

     NSLog(@"places %@", places); 
+0

什么是objectFromJSONString? – anjum 2012-02-06 13:30:35

+0

它将JSON字符串转换为对象的JSONKit方法。你用过SBJSON吗? – CarlJ 2012-02-06 13:32:39

+0

我已经导入了“JSON.h”而不是SBJSON – anjum 2012-02-06 13:35:19