9
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ネストされたJSONの取り出し方メモ

Posted at

JSONデータの解析

オブジェクトは、順序付けされない名前/値のペアのセットです。オブジェクトは、{(左の中括弧)で始まり、} (右の中括弧)で終わります。 各名前の後ろには、:(コロン)が付きます。そして、名前/値のペアは、,(コンマ)で区切られます。
JSON の紹介

{}:Dictionary
[]:Array

openWeatherMapのJSONデータからお天気をとる

openWeatherMap
{"coord": 
{"lon": 139,
"lat": 35},
"sys": 
{"message": 0.0296,
"country": "JP",
"sunrise": 1429732929,
"sunset": 1429780953},
"weather": [
{"id": 802,
"main": "Clouds",
"description": "scattered clouds",
"icon": "03d"}],
"base": "stations",
"main": 
{"temp": 287.25,
"temp_min": 287.25,
"temp_max": 287.25,
"pressure": 1026.76,
"sea_level": 1034.8,
"grnd_level": 1026.76,
"humidity": 100},
"wind": 
{"speed": 3.21,
"deg": 41.5002},
"clouds": 
{"all": 36},
"dt": 1429749965,
"id": 1851632,
"name": "Shuzenji",
"cod": 200}

ここからtempだけ取り出す場合

hoge.m
-(NSString *)getWeatherTemp:(NSString *)lat lon:(NSString *)lon{
    
    NSString *temp;
    
    NSString *ApiPath = [NSString stringWithFormat:@"http://api.openweathermap.org/data/2.5/weather?lat=%@&lon=%@",lat,lon];
    NSURL *url = [NSURL URLWithString:ApiPath];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSData *jsonData =[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(jsonData){
        NSError *jsonParsingError = nil;
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&jsonParsingError];
        NSArray *status = [dic objectForKey:@"main"];
        NSNumber *mainWeather = [status valueForKey:@"temp"];
        float code = [mainWeather floatValue];
        code = code - 273.15;//ケルビン係数なので273.15を引く
        temp = [NSString stringWithFormat:@"%.1f",code];        
    }
    return temp;
}

weatherのmainだけ取り出す

        NSArray *status = [dic objectForKey:@"weather"];
        NSArray *mainWeather = [status valueForKey:@"main"];
        NSString *string = mainWeather[0]; 
        return string;

9
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?