【发布时间】:2014-05-15 21:07:13
【问题描述】:
正如您所料,我对 obj-C 还很陌生,而且我一直在努力积累知识和经验。但我仍在为很多概念而苦苦挣扎,其中包括 JSON 数据“捕获”。 我看过很多教程和指南,但我无法将它们翻译成我需要的东西。大多数时候,他们在数组中布局数据或获取多个值,并且(当然)使用不同的变量,这让我感到困惑和不清楚,尽管这应该是愚蠢的简单。
我正在尝试做一些非常简单的事情: 从开放天气 API 中获取单个值,即温度。
我会向你展示我的代码,根据我可耻的知识,它应该是完美的,但显然它不起作用:D
@implementation HomeViewController
{
NSMutableArray *tableData;
NSDictionary *jsonDict;
NSMutableString *title;
}
-(void) viewDidLoad
{
[super viewDidLoad];
NSError *error;
//I create my data array and the string i'll store my value later on
tableData = [[NSMutableArray alloc] init];
title = [[NSMutableString alloc]init];
// Creating the link for the json api so it fits coordinates ; this works but i edited the locations out to clear the code
NSString *s = [[NSString alloc]initWithFormat:@"http://api.openweathermap.org/data/2.5/weather?lat=%.05f&lon=%.05f", _annotation.coordinate.latitude, _annotation.coordinate.longitude];
// I go online and catch the data of the url stored in S
NSData *jSonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:s]];
// This is a dictionary where all my data is stored from jsonData, keys and values all the way
jsonDict = [NSJSONSerialization JSONObjectWithData:jSonData options:NSJSONReadingMutableContainers error:&error];
// I use the string created previously and assign it the value stored in that dictionary, in the TEMP 'folder', right under MAIN.
title = [[jsonDict objectForKey:@"main"]objectForKey:@"main.temp"];
// I assign that title to a label so it appears in my view.
self.tempLabel.text = title;
...
}
给你。我可能遗漏了一些非常简单的东西,但我一直坚持这一点,即使我觉得我知道自己在做什么,我也可能遗漏了一些东西。所以如果你给我的答案,你也可以告诉我我做错了什么:D
非常感谢您的支持和知识。这个社区太棒了:)
【问题讨论】:
-
在
NSJSONSerialization行之后放置一个NSLog( @"%@", jsonDict );,并将输出添加到您的问题中。这将使人们更容易帮助您解决这个问题。
标签: ios json key-value weather-api