iOSネットワークデータ解析のJSON解析

2171 ワード

  • JSON(JavaScript Object Notation)は、言語から完全に独立したテキスト形式を採用した軽量レベルのデータ交換フォーマットであり、読み取りと作成が容易であるとともに、機械解析と
  • の生成も容易である.
  • JSONファイルには、2つの構造があります.1オブジェクト:「名前/値」ペアの集合は、「{」で始まり、「}」で終わり、名前と値の中間は「:」で2つの配列を隔てています.値のシーケンステーブルは、「[」で始まり、「」で終わり、中間はデータです.データは「,」で区切られています(JSONではデータ型:文字列、数値BOOL、オブジェクト、配列)たとえば{"reason":"success","result":[{"movieId":"215977","movieName":"森の孤影","pic_url":"http://v.juhe.cn/movie/picurl?2583247"},{"movieId":"215874","movieName":"どこから来たのか,どこへ行くのか","pic_url":"http://v.juhe.cn/movie/picurl?2583542"},{"movieId":"215823","movieName":"ある日","pic_url":"http://v.juhe.cn/movie/picurl?2583092"} ], "error_code": 0 }

  • FoundationによるJSON解析
    ステップ1:JSONファイルパスの取得ステップ2:NSDataタイプへの変換ステップ3:JSONデータコードの解析:
     
     
    • (void)jsonParser {

      //step1:

      NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"MovieList" ofType:@"txt"];

      //step2: NSData

      NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];

      //step3. json

      NSError *error;

      // :

      //NSJSONReadingMutableContainers = (1UL << 0), 。

      //NSJSONReadingMutableLeaves = (1UL << 1), NSMutableString, iOS7 。

      //NSJSONReadingAllowFragments = (1UL << 2) json , json , json 。

      NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];

      if (resultDic) {//
      // json
      if([NSJSONSerialization isValidJSONObject:resultDic]){
      // json
      NSData *strData = [NSJSONSerialization dataWithJSONObject:resultDic options:NSJSONWritingPrettyPrinted error:&error];
      // strData
      if (strData) {
      // data
      NSString *str = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
      NSLog(@"%@",str);
      }
      }
      }
      }