【发布时间】:2015-01-19 04:52:13
【问题描述】:
我似乎在通过嵌套 JSON 结果进行解析时遇到了一个小问题。如果 JSON 没有嵌套,则以下代码可以完美运行。由于每次尝试(通过其他人的例子)都失败了,我对如何继续感到有点困惑。
所以,为了测试这一点,我使用来自https://developer.worldweatheronline.com/page/explorer-free 的以下 API
我只是想获得我当前的温度 (temp_c)。
下面是调用服务的代码。请注意,我有一个 NSObject 可以填充数据,但当然我似乎无法达到那个阶段。它也是一个 NSMutableArray。同样,我认为这不是问题,但提供了上下文。
-(void)retrieveLocalWeatherService {
NSURL *url = [NSURL URLWithString:getLocalWeather];
NSData *data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//set up array and json call
weatherArray = [[NSMutableArray alloc]init];
//Loop through the JSON array
for (int i = 0; i< jsonArray.count; i++)
{
//create our object
NSString *nTemp = [[jsonArray objectAtIndex:i]objectForKey:@"temp_C"];
NSString *nPressure = [[jsonArray objectAtIndex:i]objectForKey:@"pressure"];
NSString *nHumidity = [[jsonArray objectAtIndex:i]objectForKey:@"humidity"];
//Add the object to our animal array
[weatherArray addObject:[[LocalWeather alloc]initWithtemp:(nTemp) andpressure:nPressure andhumidity:nHumidity]];
}
这是 JSON 响应。
{
"data": {
"current_condition": [
{
"cloudcover": "75",
"FeelsLikeC": "31",
"FeelsLikeF": "88",
"humidity": "70",
"observation_time": "05:15 AM",
"precipMM": "0.0",
"pressure": "1011",
"temp_C": "28",
"temp_F": "82",
"visibility": "10",
"weatherCode": "116",
"weatherDesc": [
{
"value": "Partly Cloudy"
}
],
"weatherIconUrl": [
{
"value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png"
}
],
"winddir16Point": "N",
"winddirDegree": "10",
"windspeedKmph": "41",
"windspeedMiles": "26"
}
],
"request": [
{
"query": "Brisbane, Australia",
"type": "City"
}
],
我在运行数英里时切断了 JSON 服务,那么我哪里出错了?我相信它在“for-loop”中的某个地方,但不确定在哪里。我知道它的主要节点是“数据”,然后子节点是“current_condition”。我应该挖掘 JSON 结果吗?如果什么是最好的方法。
顺便说一句,我收到来自服务器的响应,其中包含整个 JSON 结果。显然是我的解析问题。
提前致谢! 请善待我是新手。
【问题讨论】:
标签: objective-c json nsdata nsurl