首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SBJson显示null

SBJson显示null
EN

Stack Overflow用户
提问于 2013-04-18 18:44:52
回答 3查看 548关注 0票数 0

我正在尝试用SBJson解析一些json数据来显示当前的温度。本教程中的示例代码运行良好:Tutorial: Fetch and parse JSON

当我将代码更改为我的json提要时,我得到一个null。我对JSON比较陌生,但我已经阅读了我找到的所有教程和文档。我使用的json源代码:JSON Source

我用sbjson编写的代码:

代码语言:javascript
复制
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代码。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-04-18 18:49:29

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

代码语言:javascript
复制
{ "data": { "current_condition": [ { ..., "temp_C": "7", ... } ], ... } }

这是一个可视化的表示:

因此,要获得temp_C,您需要首先获取顶级data属性:

代码语言:javascript
复制
NSDictionary* json = (NSDictionary*)[responseString JSONValue];
NSDictionary* data = [json objectForKey:@"data"];

然后,从中获取current_location属性:

代码语言:javascript
复制
NSArray* current_condition = [data objectForKey:@"current_condition"];

最后,从current_location数组中获取您感兴趣的元素:

代码语言:javascript
复制
NSDictionary* weathernow = [current_condition objectAtIndex:0];

还要注意,temp_CweatherCode是字符串,而不是数字。将它们转换为数字,而不是:

代码语言:javascript
复制
NSNumber* tempc = [weathernow objectForKey:@"temp_C"];
NSNumber* weatherCode = [weathernow objectForKey:@"weatherCode"];

你可以使用类似这样的东西:

代码语言:javascript
复制
int tempc = [[weathernow objectForKey:@"temp_C"] intValue];
int weatherCode = [[weathernow objectForKey:@"weatherCode"] intValue];

(如果值不是int,而是floatdouble,则为floatValue / doubleValue )

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

代码语言:javascript
复制
NSLog(@"%d %d", tempc, weatherCode);
票数 2
EN

Stack Overflow用户

发布于 2013-04-18 18:49:47

使用NSJSONSerialization而不是JSONValue

代码语言:javascript
复制
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary* jsonDict = [NSJSONSerialization
                                      JSONObjectWithData:data
                                      options:kNilOptions
                                      error:&error];
 NSLog(@"jsonDict:%@",jsonDict);

在您的链接中,没有current_weather密钥。

代码语言:javascript
复制
NSString* tempc = [[[[jsonDict objectForKey:@"data"] objectForKey:@"current_condition"] objectAtIndex:0] objectForKey:@"temp_C"];
票数 0
EN

Stack Overflow用户

发布于 2013-04-18 18:50:14

提供的链接返回不带current_weather参数的json。仅有current_condition参数,请查看此信息。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16080809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档