最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Objective-C Json 实例详解
时间:2022-06-26 05:54:14 编辑:袖梨 来源:一聚教程网
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
相关文章
- QQ经典版app最新版本下载-QQ经典版app官方正版iOS苹果版下载入口 03-14
- picacg哔咔下载入口-PicACG官方导航 03-14
- 番茄免费全本小说畅读-番茄免费全本小说完结畅读 03-14
- 小米云服务入口在哪-小米云服务官网登录地址详解 03-14
- 漫蛙漫画官方登录入口-漫蛙2漫画app免费下载 03-14
- picacg哔咔注册验证?2026picacg哔咔一键注册指南 03-14