0

我正在尝试使用 SBJson 解析一些 json 数据以显示当前温度。本教程中的示例代码完美运行:教程:获取和解析 JSON

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

4

3 回答 3

2

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

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

这是一个视觉表示:

JSON 视觉表示

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

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如果值不应该是 a int,而是 afloat或 a double

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

NSLog(@"%d %d", tempc, weatherCode);
于 2013-04-18T10:49:29.197 回答
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"];
于 2013-04-18T10:49:47.437 回答
0

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

于 2013-04-18T10:50:14.313 回答