iOSデータ解析のJSON解析

4257 ワード

  • 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
    
     }

    JSON解析手順を行う
  • JSONファイルパス
  • を取得
  • NSDataタイプ
  • に変換
  • 解析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);
          }
        }
      }
    }