SBJson显示为null

时间:2013-04-18 10:44:52

标签: ios json sbjson

我正在尝试用SBJson解析一些json数据以显示当前温度。本教程中的示例代码非常完美:Tutorial: Fetch and parse JSON

当我将代码更改为我的json feed时,我得到一个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代码。

3 个答案:

答案 0 :(得分:2)

您发布的JSON数据中没有current_weather个密钥。结构是:

{ "data": { "current_condition": [ { ..., "temp_C": "7", ... } ], ... } }

这是一个直观的表示:

JSON visual representation

因此,要获得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_CweatherCode是字符串,而不是数字。要将它们转换为数字,而不是:

NSNumber* tempc = [weathernow objectForKey:@"temp_C"];
NSNumber* weatherCode = [weathernow objectForKey:@"weatherCode"];

你可以使用类似的东西:

int tempc = [[weathernow objectForKey:@"temp_C"] intValue];
int weatherCode = [[weathernow objectForKey:@"weatherCode"] intValue];

(或floatValue / doubleValue如果该值不应该是int,而是floatdouble

然后,您可以使用%d(或%f作为float / double)作为格式字符串:

NSLog(@"%d %d", tempc, weatherCode);

答案 1 :(得分:0)

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

答案 2 :(得分:0)

提供的链接返回没有current_weather参数的json。只有current_condition参数,请查看此内容。