我正在尝试用SBJson解析一些json数据来显示当前的温度。本教程中的示例代码运行良好:Tutorial: Fetch and parse JSON
当我将代码更改为我的json提要时,我得到一个null。我对JSON比较陌生,但我已经阅读了我找到的所有教程和文档。我使用的json源代码:JSON Source
我用sbjson编写的代码:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
NSArray* currentw = [(NSDictionary*)[responseString JSONValue] objectForKey:@"current_weather"];
//choose a random loan
NSDictionary* weathernow = [currentw objectAtIndex:0];
//fetch the data
NSNumber* tempc = [weathernow objectForKey:@"temp_C"];
NSNumber* weatherCode = [weathernow objectForKey:@"weatherCode"];
NSLog(@"%@ %@", tempc, weatherCode);当然,我已经实现了其他sbjson代码。
发布于 2013-04-18 18:49:29
您发布的JSON数据中没有current_weather密钥。它的结构是:
{ "data": { "current_condition": [ { ..., "temp_C": "7", ... } ], ... } }这是一个可视化的表示:

因此,要获得temp_C,您需要首先获取顶级data属性:
NSDictionary* json = (NSDictionary*)[responseString JSONValue];
NSDictionary* data = [json objectForKey:@"data"];然后,从中获取current_location属性:
NSArray* current_condition = [data objectForKey:@"current_condition"];最后,从current_location数组中获取您感兴趣的元素:
NSDictionary* weathernow = [current_condition objectAtIndex:0];还要注意,temp_C和weatherCode是字符串,而不是数字。将它们转换为数字,而不是:
NSNumber* tempc = [weathernow objectForKey:@"temp_C"];
NSNumber* weatherCode = [weathernow objectForKey:@"weatherCode"];你可以使用类似这样的东西:
int tempc = [[weathernow objectForKey:@"temp_C"] intValue];
int weatherCode = [[weathernow objectForKey:@"weatherCode"] intValue];(如果值不是int,而是float或double,则为floatValue / doubleValue )
然后使用%d (对于float /double,使用%f )作为格式字符串:
NSLog(@"%d %d", tempc, weatherCode);发布于 2013-04-18 18:49:47
使用NSJSONSerialization而不是JSONValue。
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(@"jsonDict:%@",jsonDict);在您的链接中,没有current_weather密钥。
NSString* tempc = [[[[jsonDict objectForKey:@"data"] objectForKey:@"current_condition"] objectAtIndex:0] objectForKey:@"temp_C"];发布于 2013-04-18 18:50:14
提供的链接返回不带current_weather参数的json。仅有current_condition参数,请查看此信息。
https://stackoverflow.com/questions/16080809
复制相似问题