ios下解析json字串

來源:互聯網
上載者:User

在ios下解析json可以使用官方的庫,https://github.com/johnezang/JSONKit

包裡只有兩個檔案,jsonkit.h/jsonkit.m包含到類裡面即可

//使用一個json字串來作為被解析對象

NSString *jsonstring =
@"[{\"age\":18,\"book\":{\"price\":23.2,\"title\":\"booooooook1\"},\"name\":\"samyou\"},{\"age\":22,\"book\":{\"price\":21,\"title\":\"booooooook2\"},\"name\":\"samsam\"}]";

//轉換為nsdata為了類比從http得到的json資料類型

NSData *data = [jsonstring   dataUsingEncoding:NSUTF8StringEncoding];

//如果json串最外層是jsonarray則用mutableObjectFromJSONData,返回NSArray,否則用objectFromJSONData,返回NSDictionary

NSArray *arr = (NSArray *)[data  mutableObjectFromJSONData];

NSLog(@"count=%d",arr.count);

for(int i=0;i<arr.count;i++)

{

NSDictionary *people = [arr   objectAtIndex:i];

NSString *name = [people   objectForKey:@"name"];

NSNumber *age = [people  objectForKey:@"age"];//NSDictionary不能儲存基礎資料型別 (Elementary Data Type),所以所有的基礎資料型別 (Elementary Data Type)都是通過NSNumber封裝

NSLog(@"person withname=%@,age = %d",name,[age   intValue]);

NSDictionary *book = [people  objectForKey:@"book"];

NSString *bookname = [book  objectForKey:@"title"];

NSNumber *price = [book  objectForKey:@"price"];

NSLog(@"book with title=%@, price=%f",bookname,[price   doubleValue]);

}

哥的原始碼

http://download.csdn.net/detail/samguoyi/4286190

相關文章

聯繫我們

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