Objective-C Json 实例详解
2019/7/9 22:49:52
本文主要是介绍Objective-C Json 实例详解,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
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."); }
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
这篇关于Objective-C Json 实例详解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-08-29Axios库资料:新手入门指南与基本使用教程
- 2024-03-14system bios shadowed
- 2024-03-14gabios
- 2024-02-07iOS应用提交上架的最新流程
- 2024-02-06打包 iOS 的 IPA 文件
- 2023-12-07uniapp打包iOS应用并通过审核:代码混淆的终极解决方案 ?
- 2023-11-25uniapp IOS从打包到上架流程(详细简单) 原创
- 2023-11-10【iOS开发】iOS App的加固保护原理:使用ipaguard混淆加固
- 2023-09-30最强大的iOS应用源码保护工具:Ipa Guard,保护你的商业机密代码
- 2023-09-07iOS安全加固探讨:代码混淆、类名方法名混淆等方法