iOS資料解析之JSON解析

來源:互聯網
上載者:User

標籤:

  • JSON(JavaScript Object Notation)是一種輕量級的資料交換格式,採用完全獨立於語言的文字格式設定,易於閱讀和編寫,同時也易於機器解析和產生
  • JSON檔案有兩種結構:
    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解析步驟

  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);      }    }  }}

iOS資料解析之JSON解析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.