在Obj-C中获取JSON值

时间:2015-12-01 11:45:24

标签: ios objective-c nsdictionary

我在访问与我在教程中找到的JSON对象不同的JSON对象时遇到了麻烦:

我在教程中使用了这个JSON:

{
"coord": {
    "lon": -0.13,
    "lat": 51.51
},
"weather": [{
    "id": 803,
    "main": "Clouds",
    "description": "broken clouds",
    "icon": "04d"
}],
"base": "cmc stations",
"main": {
    "temp": 285.325,
    "pressure": 1024.67,
    "humidity": 95,
    "temp_min": 285.325,
    "temp_max": 285.325,
    "sea_level": 1034.69,
    "grnd_level": 1024.67
},
"wind": {
    "speed": 7.46,
    "deg": 246.001
},
"clouds": {
    "all": 76
},
"dt": 1448967456,
"sys": {
    "message": 0.0027,
    "country": "GB",
    "sunrise": 1448955837,
    "sunset": 1448985295
},
"id": 2643743,
"name": "London",
"cod": 200

}

为了从中获取主要价值,我使用此代码:

 NSURLRequest *urlrequest =[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.openweathermap.org"]];

NSURLSession *session = [NSURLSession sharedSession];

[[session dataTaskWithRequest:urlrequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    NSMutableDictionary *allData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

    NSString* currentWeather = nil;

    NSArray* weather = allData[@"weather"];

    for (NSDictionary* weatherDictionary in weather){
        currentWeather = weatherDictionary[@"main"];
    }

    [self setImageAndTextWithWeather:currentWeather];

    //NSLog(allData[@"temp_c"]);

}] resume];

这很好用。 但是现在我正试图从另一个源访问JSON对象,如下所示:

  {
"response": {
    "version": "0.1",
    "termsofService": "http://www.wunderground.com/weather/api/d/terms.html",
    "features": {
        "conditions": 1
    }
},
"current_observation": {
    "image": {
        "url": "http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",
        "title": "Weather Underground",
        "link": "http://www.wunderground.com"
    },
    "display_location": {
        "full": "San Francisco, CA",
        "city": "San Francisco",
        "state": "CA",
        "state_name": "California",
        "country": "US",
        "country_iso3166": "US",
        "zip": "94101",
        "latitude": "37.77500916",
        "longitude": "-122.41825867",
        "elevation": "47.00000000"
    },
    "observation_location": {
        "full": "SOMA - Near Van Ness, San Francisco, California",
        "city": "SOMA - Near Van Ness, San Francisco",
        "state": "California",
        "country": "US",
        "country_iso3166": "US",
        "latitude": "37.773285",
        "longitude": "-122.417725",
        "elevation": "49 ft"
    },
    "estimated": {},
    "station_id": "KCASANFR58",
    "observation_time": "Last Updated on June 27, 5:27 PM PDT",
    "observation_time_rfc822": "Wed, 27 Jun 2012 17:27:13 -0700",
    "observation_epoch": "1340843233",
    "local_time_rfc822": "Wed, 27 Jun 2012 17:27:14 -0700",
    "local_epoch": "1340843234",
    "local_tz_short": "PDT",
    "local_tz_long": "America/Los_Angeles",
    "local_tz_offset": "-0700",
    "weather": "Partly Cloudy",
    "temperature_string": "66.3 F (19.1 C)",
    "temp_f": 66.3,
    "temp_c": 19.1,
    "relative_humidity": "65%",
    "wind_string": "From the NNW at 22.0 MPH Gusting to 28.0 MPH",
    "wind_dir": "NNW",
    "wind_degrees": 346,
    "wind_mph": 22.0,
    "wind_gust_mph": "28.0",
    "wind_kph": 35.4,
    "wind_gust_kph": "45.1",
    "pressure_mb": "1013",
    "pressure_in": "29.93",
    "pressure_trend": "+",
    "dewpoint_string": "54 F (12 C)",
    "dewpoint_f": 54,
    "dewpoint_c": 12,
    "heat_index_string": "NA",
    "heat_index_f": "NA",
    "heat_index_c": "NA",
    "windchill_string": "NA",
    "windchill_f": "NA",
    "windchill_c": "NA",
    "feelslike_string": "66.3 F (19.1 C)",
    "feelslike_f": "66.3",
    "feelslike_c": "19.1",
    "visibility_mi": "10.0",
    "visibility_km": "16.1",
    "solarradiation": "",
    "UV": "5",
    "precip_1hr_string": "0.00 in ( 0 mm)",
    "precip_1hr_in": "0.00",
    "precip_1hr_metric": " 0",
    "precip_today_string": "0.00 in (0 mm)",
    "precip_today_in": "0.00",
    "precip_today_metric": "0",
    "icon": "partlycloudy",
    "icon_url": "http://icons-ak.wxug.com/i/c/k/partlycloudy.gif",
    "forecast_url": "http://www.wunderground.com/US/CA/San_Francisco.html",
    "history_url": "http://www.wunderground.com/history/airport/KCASANFR58/2012/6/27/DailyHistory.html",
    "ob_url": "http://www.wunderground.com/cgi-bin/findweather/getForecast?query=37.773285,-122.417725"
}

} 现在我如何获得temp_c值?

我做了NSLog(allData)@"temp_c" : (double)26.9 我可能正试图以NSString双倍值存储吗?

我尝试将当前代码中的值更改为allData[@"current_observation"]weatherDictonary[@"temp_c"],但我总是出错。

2 个答案:

答案 0 :(得分:1)

“current_observation”不包含数组,它包含Dictionary

NSDictionary* weather = allData[@"current_observation"];
NSString *currentWeather = nil;
NSString *currentTemp = nil;
if (weather[@"temperature_string"]){
    currentWeather = weather[@"temperature_string"];
}
if (weather[@"temp_c"]) {
    currentTemp = [NSString stringWithFormat:@"%@",weather[@"temp_c"]];
}

“temp_c”是一个数字而不是字符串,因此您需要将其强制转换为字符串。

答案 1 :(得分:-1)

在之前的评论中,对您的问题并不是很好的解释。您有NSDictionary而不是NSArray。简单的解决方案就是迭代:

NSString *weather =[NSString stringWithFormat:@"%@", [allData objectForKeyPath:@"temp_c"]];