【问题标题】:SBJson displays nullSBJson 显示为空
【发布时间】:2013-04-18 10:44:51
【问题描述】:

我正在尝试使用 SBJson 解析一些 json 数据以显示当前温度。本教程中的示例代码完美运行:Tutorial: Fetch and parse 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 代码。

【问题讨论】:

  • 如果这是一个新项目,应该考虑使用苹果官方NSJSONSerialization。
  • 了解如何读取 JSON——可能需要 5 分钟:json.org
  • 与您的问题相矛盾SBJson 不显示任何内容。它只是用于解析 JSon。

标签: ios json sbjson


【解决方案1】:

您发布的 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];

(或floatValue / doubleValue,如果值不应该是int,而是float 或double)

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

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

【讨论】:

  • 谢谢我成功了!!您提供的代码中有一个小问题: NSDictioanry* current_condition = [data objectForKey:@"current_condition"];需要为:NSArray *currentConditions = [data objectForKey:@"current_condition"];
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-19
      • 1970-01-01
      • 2015-04-14
      相关资源
      最近更新 更多