IOS學習筆記38——NSJSONSerialization使用

來源:互聯網
上載者:User

 關於NSJSONSerialization,官方文檔中有如下介紹:You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON. An object that may be converted to JSON must have the following properties: The top level object is an NSArray or NSDictionary.All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.All dictionary keys are instances of NSString.Numbers are not NaN or infinity.我們能利用NSJSONSerialization將JSON轉換成Foundation對象,也能將Foundation對象轉換成JSON,轉換成JSON的對象必須具有如下屬性:頂層對象必須是NSArray或者NSDictionary所有的對象必須是NSString、NSNumber、NSArray、NSDictionary、NSNull的執行個體所有NSDictionary的key必須是NSString類型數字對象不能是非數值或無窮 接下來看看如何使用,首先是如何產生JSON格式的資料:我這裡選用項目中的程式碼片段來進行簡要介紹,以下顯示了登陸請求JSON格式資料的產生[cpp] NSDictionary *registerDic = [NSDictionary dictionaryWithObjectsAndKeys:uuid,@"_id",userName,@"login_name",password,@"password", nil];      if ([NSJSONSerialization isValidJSONObject:registerDic]) {          NSError *error;          NSData *registerData = [NSJSONSerialization dataWithJSONObject:registerDic options:NSJSONWritingPrettyPrinted error:&error];          NSLog(@"Register JSON:%@",[[NSString alloc] initWithData:registerData encoding:NSUTF8StringEncoding]);      }   NSDictionary中的key就是json字串中的key,object就是json字串中的value,isValidJSONObject:方法是檢測Foundation對象能否合法轉換為JSON對象,dataWithJSONObject:options:error方法是將Foundation對象轉換為JSON對象,參數NSJSONWritingPrettyPrinted的意思是將產生的json資料格式化輸出,這樣可讀性高,不設定則輸出的json字串就是一整行。 解析服務端返回的json格式資料:[cpp]  NSDictionary *resultJSON = [NSJSONSerialization JSONObjectWithData:resultData options:kNilOptions error:&error];   擷取返回字串中key為status的value:[cpp]  NSString *status = [resultJSON objectForKey:@"status"];   以上就簡要的介紹了下NSJSONSerilazation的使用,不是很全面,以後有時間再深入詳解一下。

相關文章

聯繫我們

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