JSON解析步驟

來源:互聯網
上載者:User

JSON解析步驟

解析:就是按照一種約定好的格式(假象),由後台開發人員按照格式存資料,由前端開發人員按照格式取資料.(謹記:這種格式是由後台開發人員決定的,我們無權決定)

解析的本質:按照約定好的格式,取出我們想要的資料的過程.


JSON解析系統

1.先擷取檔案路徑

NSString *jsonPath = [[NSBundlemainBundle]pathForResource:@"Student" ofType:@"json"];

2.初始化NSData對象

NSData *data = [NSDatadataWithContentsOfFile:jsonPath];

3.解析(資料最外層是什麼類型,就用什麼類型,如下)

NSMutableArray *arr = [NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingMutableContainerserror:nil];


對於JSONKit提供的解析方式是為NSString,NSData添加分類的方式,在分類中添加瞭解析的方法,將json格式資料解析成NSArray,NSDictionary.效率僅次於系統提供的方法.
而為NSArray,NSDictionary添加的分類的方法,則是將OC的對象,轉化為JSON格式字串.

一.將OC的數群組轉換成json格式

NSArray *arr =@[@"aa",@"bb",@"cc",@"dd",@"ee"];

轉化

NSString *jsonStr = [arrJSONString];

二.將字典轉化為JSON格式
NSDictionary *dic =@{@"name":@"Frank",@"gender":@"man",@"age":@"18"};
NSString *jsonStr = [dicJSONString];

三.NSString解析

1.先擷取檔案路徑

NSString *jsonPath = [[NSBundlemainBundle]pathForResource:@"Student"ofType:@"json"];

2.初始化NSString對象

NSString *jsonStr = [NSStringstringWithContentsOfFile:jsonPathencoding:NSUTF8StringEncodingerror:nil];

3.解析

NSArray *arr = [jsonStrobjectFromJSONString];


四. NSData解析

1.先擷取檔案路徑

NSString *jsonPath = [[NSBundlemainBundle]

pathForResource:@"Student"ofType:@"json"];

2.初始化NSData對象

NSData *data = [NSDatadataWithContentsOfFile:jsonPath];

3.解析

NSArray *arr = [dataobjectFromJSONData];

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.