国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > iOS > 正文

Objective-C Json 實例詳解

2020-07-26 02:38:34
字體:
來源:轉載
供稿:網友

Objective-C Json 實例詳解

通過使用NSJSONSerialization 可以Json與Foundation的相互轉換。下面具體介紹 Objective-c json 的使用。

Json To Fundation

使用 JSONObjectWithData 可以將 Json 轉化為 Foundation。Json的頂層可以是{} 或 []因此可以有 NSDictionary 和 NSArray 兩種格式。讀取使用 ObjectForKey 返回對應的對象。

NSString* items = @"{"items":["item0","item1","item2"]}"; NSData *data= [items dataUsingEncoding:NSUTF8StringEncoding]; NSError *error = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData:data           options:NSJSONReadingAllowFragments           error:&error]; if ([jsonObject isKindOfClass:[NSDictionary class]]){   NSDictionary *dictionary = (NSDictionary *)jsonObject;   NSLog(@"Dersialized JSON Dictionary = %@", dictionary); }else if ([jsonObject isKindOfClass:[NSArray class]]){   NSArray *nsArray = (NSArray *)jsonObject;   NSLog(@"Dersialized JSON Array = %@", nsArray); } else {   NSLog(@"An error happened while deserializing the JSON data."); } NSDictionary *dict = (NSDictionary *)jsonObject; NSArray* arr = [dict objectForKey:@"items"];NSLog(@"list is %@",arr);

Fundation To Json

使用 dataWithJsonObject 可以將 Fundation 轉換為 Json。其中 options:NSJSONWritingPrettyPrinted 是分行輸出json ,無空格輸出使用 option:kNilOptions。

下面這段代碼是IOS內購獲取商品列表。獲取后,將內容添加到Json中。

NSArray *myProduct = response.products;NSDictionary *myDict;NSMutableDictionary *dict = [NSMutableDictionary                 dictionaryWithCapacity: 4]; for(int i = 0;i<myProduct.count;++i){   //NSLog(@"----------------------");  //NSLog(@"Product title: %@" ,[myProduct[i] localizedTitle]);  //NSLog(@"Product description: %@" ,[myProduct[i] localizedDescription]);  //NSLog(@"Product price: %@" ,[myProduct[i] price]);  //NSLog(@"Product id: %@" ,[myProduct[i] productIdentifier]);   myDict = [NSDictionary dictionaryWithObjectsAndKeys:          [myProduct[i] localizedTitle], @"title",          [myProduct[i] localizedDescription], @"desc",          [myProduct[i] price], @"price",          [myProduct[i] productIdentifier], @"product", nil];   [dict setValue: myDict forKey: [myProduct[i] productIdentifier]];}if([NSJSONSerialization isValidJSONObject:dict]){  NSError* error;  NSData *str = [NSJSONSerialization dataWithJSONObject:dict             options:kNilOptions error:&error];  NSLog(@"Result: %@",[[NSString alloc]initWithData:str               encoding:NSUTF8StringEncoding]);}else{  NSLog(@"An error happened while serializing the JSON data.");}    

 如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 蓬安县| 吉木萨尔县| 黄山市| 云阳县| 达日县| 大同市| 沐川县| 六枝特区| 全南县| 饶平县| 乌兰浩特市| 沅陵县| 阿坝县| 尼玛县| 彭州市| 鞍山市| 安吉县| 富蕴县| 达拉特旗| 崇州市| 馆陶县| 洪雅县| 印江| 旌德县| 福贡县| 枞阳县| 兴宁市| 龙川县| 文山县| 漳浦县| 汕尾市| 山东省| 灵寿县| 新疆| 武清区| 自贡市| 澎湖县| 彰武县| 陕西省| 汾西县| 峡江县|