iOS-JSONデータ解フォーマット

3064 ワード

jsonデータ解析
jsonの概念
JSON(JavaScript Object Notation)は、軽量レベルのデータ交換フォーマットです.実際の開発ではJSONを使用してサーバ上のデータを取得したり、jsonデータを解析して欲しいデータを取得したりすることがよくあります
iOS開発NSJSONSSerialization(シーケンス化)クラス解析jsonデータNSJSONSSerializationを用いてJsonデータパッケージ、Jsonデータ解析を提供
NSJSONSSerializationは、JSONデータをNSDictionaryまたはNSArrayデパッケージング方法に変換し、NSDictionary、NSArrayオブジェクトをJSONデータに変換する(isValidJSOnObjectを呼び出すことでNSDictionary、NSArrayオブジェクトがJSONデータに変換できるか否かを判断できる)パッケージング
jsonデータパッケージ
   NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2",@"value3",@"key3", nil];

      // isValidJSONObject           json  
      if ([NSJSONSerialization isValidJSONObject:dic]){
          NSError *error;

          //     json Data, NSJSONWritingPrettyPrinted   JSON      ,        。
          NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];

          NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
          NSLog(@"json data:%@",json);
      }


jsonデータ解析
  NSError *error;
  //    NSURL  
  NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.weather.com.cn/data/101120101.html"]];

  //    url    NSData   
  NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];  
  
//iOS     NSJSONSerialization response           
  NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];

  NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"];

  NSString *text = [NSString stringWithFormat:@"    %@  %@  %@        :%@  %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];    NSLog(@"weatherInfo:%@", text );

json解析プロセスの例
  NSError *error;
//    NSURL  
NSURLRequest\*request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://m.weather.com.cn/data/101180601.html"]];

//    url    NSData   
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

//iOS     NSJSONSerialization response           
NSDictionary *weatherDic = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];

NSDictionary *weatherInfo = [weatherDic objectForKey:@"weatherinfo"];

txtView.text = [NSString stringWithFormat:@"    %@ %@ %@       :%@ %@ ",[weatherInfo objectForKey:@"date_y"],[weatherInfo objectForKey:@"week"],[weatherInfo objectForKey:@"city"], [weatherInfo objectForKey:@"weather1"], [weatherInfo objectForKey:@"temp1"]];

NSLog(@"weatherInfo        ---%@", weatherDic );