栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > iOS

Objective-C Json 实例详解

iOS 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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.");
}    

 如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/166432.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号