iosjson 数组类型转对象存放对象类型 怎么转dic

IOS开发(75)之把 JSON 数据转化成 Arrays 或者 Dictionaries
通过 NSJSONSerialization 这个类的 JSONObjectWithData:options:error:方法来实现,把JSON 数据解析出来放在数据或者字典里面保存。
2 代码示例
TestDemo.m
-(void)convseFromJson{&
&&& NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];&
&&& [dictionary setValue:@&Anthony& forKey:@&First Name&];&
&&& [dictionary setValue:@&Robbins& forKey:@&Last Name&];&
&&& [dictionary setValue:[NSNumber numberWithUnsignedInteger:51] forKey:@&Age&];&
&&& NSArray *arrayOfAnthonysChildren = [[NSArray alloc] initWithObjects:&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& @&Anthony's Son 1&,&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& @&Anthony's Daughter 1&,&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& @&Anthony's Son 2&,&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& @&Anthony's Son 3&,&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& @&Anthony's Daughter 2&, nil];&
&&& [dictionary setValue:arrayOfAnthonysChildren forKey:@&children&];&
&&& NSError *error =&
&&& NSData *jsonData = [NSJSONSerialization&
&&&&&&&&&&&&&&&&&&&&&&& dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];&
&&& if ([jsonData length] & 0 && error == nil){&
&&&&&&& NSLog(@&Successfully serialized the dictionary into data.&);&
&&&&&&& /* Json转数组/字典 */&
&&&&&&& error =&
&&&&&&& //转换方法&
&&&&&&& id jsonObject = [NSJSONSerialization&
&&&&&&&&&&&&&&&&&&&&&&&& JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments&
&&&&&&&&&&&&&&&&&&&&&&&& error:&error];&
&&&&&&& if (jsonObject != nil && error == nil){&
&&&&&&&&&&& NSLog(@&Successfully deserialized...&);&
&&&&&&&&&&& //如果jsonObject是字典类&
&&&&&&&&&&& if ([jsonObject isKindOfClass:[NSDictionary class]]){&
&&&&&&&&&&&&&&& NSDictionary *deserializedDictionary = (NSDictionary *)jsonO&
&&&&&&&&&&&&&&& NSLog(@&Dersialized JSON Dictionary = %@&, deserializedDictionary);&
&&&&&&&&&&& }&
&&&&&&&&&&& //如果jsonObject是数组类&
&&&&&&&&&&& else if ([jsonObject isKindOfClass:[NSArray class]]){&
&&&&&&&&&&&&&&& NSArray *deserializedArray = (NSArray *)jsonO&
&&&&&&&&&&&&&&& NSLog(@&Dersialized JSON Array = %@&, deserializedArray);&
&&&&&&&&&&& } else {&
&&&&&&&&&&&&&&& NSLog(@&I can't deal with it&);&
&&&&&&&&&&& }&
&&&&&&& }&
&&&&&&& else if (error != nil){&
&&&&&&&&&&& NSLog(@&An error happened while deserializing the JSON data.&); }&
&&& else if ([jsonData length] == 0 &&error == nil){&
&&&&&&& NSLog(@&No data was returned after serialization.&);&
&&& else if (error != nil){&
&&&&&&& NSLog(@&An error happened = %@&, error);&
-(void)convseFromJson{
&&& NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
&&& [dictionary setValue:@&Anthony& forKey:@&First Name&];
&&& [dictionary setValue:@&Robbins& forKey:@&Last Name&];
&&& [dictionary setValue:[NSNumber numberWithUnsignedInteger:51] forKey:@&Age&];
&&& NSArray *arrayOfAnthonysChildren = [[NSArray alloc] initWithObjects:
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& @&Anthony's Son 1&,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& @&Anthony's Daughter 1&,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& @&Anthony's Son 2&,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& @&Anthony's Son 3&,
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& @&Anthony's Daughter 2&, nil];
&&& [dictionary setValue:arrayOfAnthonysChildren forKey:@&children&];
&&& NSError *error =
&&& NSData *jsonData = [NSJSONSerialization
&&&&&&&&&&&&&&&&&&&&&&& dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
&&& if ([jsonData length] & 0 && error == nil){
&&&&&&& NSLog(@&Successfully serialized the dictionary into data.&);
&&&&&&& /* Json转数组/字典 */
&&&&&&& error =
&&&&&&& //转换方法
&&&&&&& id jsonObject = [NSJSONSerialization
&&&&&&&&&&&&&&&&&&&&&&&& JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments
&&&&&&&&&&&&&&&&&&&&&&&& error:&error];
&&&&&&& if (jsonObject != nil && error == nil){
&&&&&&&&&&& NSLog(@&Successfully deserialized...&);
&&&&&&&&&&& //如果jsonObject是字典类
&&&&&&&&&&& if ([jsonObject isKindOfClass:[NSDictionary class]]){
&&&&&&&&&&&&&&& NSDictionary *deserializedDictionary = (NSDictionary *)jsonO
&&&&&&&&&&&&&&& NSLog(@&Dersialized JSON Dictionary = %@&, deserializedDictionary);
&&&&&&&&&&& }
&&&&&&&&&&& //如果jsonObject是数组类
&&&&&&&&&&& else if ([jsonObject isKindOfClass:[NSArray class]]){
&&&&&&&&&&&&&&& NSArray *deserializedArray = (NSArray *)jsonO
&&&&&&&&&&&&&&& NSLog(@&Dersialized JSON Array = %@&, deserializedArray);
&&&&&&&&&&& } else {
&&&&&&&&&&&&&&& NSLog(@&I can't deal with it&);
&&&&&&&&&&& }
&&&&&&& else if (error != nil){
&&&&&&&&&&& NSLog(@&An error happened while deserializing the JSON data.&); }
&&& else if ([jsonData length] == 0 &&error == nil){
&&&&&&& NSLog(@&No data was returned after serialization.&);
&&& else if (error != nil){
&&&&&&& NSLog(@&An error happened = %@&, error);
控制台结果
17:26:15.726 FromJsonTest[] Successfully serialized the dictionary into data.
17:26:15.728 FromJsonTest[] Successfully deserialized...
17:26:15.728 FromJsonTest[] Dersialized JSON Dictionary = {
&&& Age = 51;
&&& &First Name& = A
&&& &Last Name& = R
&&& children =&&&& (
&&&&&&& &Anthony's Son 1&,
&&&&&&& &Anthony's Daughter 1&,
&&&&&&& &Anthony's Son 2&,
&&&&&&& &Anthony's Son 3&,
&&&&&&& &Anthony's Daughter 2&
(window.slotbydup=window.slotbydup || []).push({
id: '2467140',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467141',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467142',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467143',
container: s,
size: '1000,90',
display: 'inlay-fix'
(window.slotbydup=window.slotbydup || []).push({
id: '2467148',
container: s,
size: '1000,90',
display: 'inlay-fix'首先讲objective-c如何实现:
这里需要用到2个,一个是JSONKit,另一个是Jastor,一共包含6个文件,3个.h头文件和3个.m实现文件。在ARC的工程中如何导入不支持ARC的第三方工具请看这篇文章:
具体文件在网上都比较好找,自己去下载即可。
NSObject类型的json字符串转换为对象
大体的思路是这样,首先将json字符串先转化成NSDictionary,然后再通过参数是NSDictionary的初始化方法来生成相应的对象。
其中生成NSDictionary的过程是由JSONKit提供的NSString的objectFromJSONString方法来完成的。
而将NSDictionary生成相应对象的过程是有Jastor来完成,这个过程有几个要求:
你的对象必须继承Jastor对象;
你的对象的属性名必须和json字符串的属性名称对应;
如果你的对象中包含自定义对象的列表,则需要为这个属性单独写一个类方法,规则是"属性名_class";
例子如下:
JSON字符串的结构如下图:
其中包含一个班级的信息,和班级中的3个学生的信息。
对应的数据结构如下:
BMclass.h:
@interface BMClass : Jastor
@property (strong,nonatomic) NSString*
@property (strong,nonatomic) NSString*
@property (strong,nonatomic) NSArray*
+(id)students_
BMclass.m:
@implementation BMClass
@synthesize name,grade,
+(id)students_class{
return [BMStudent class];
BMStudent.h:
@interface BMStudent : Jastor
@property (strong,nonatomic) NSString*
@property (strong,nonatomic) NSString*
@property (nonatomic)
BMStudent.m:
@implementation BMStudent
@synthesize name,age,
具体的解析代码如下:
NSDictionary* dic = [jsonStr objectFromJSONString];
BMClass* c = [[BMClass alloc]initWithDictionary:dic];
运行后的解析的结果如下图(Debug的截图):
NSArray类型的json字符串转换为对象&
如果您获得的字符串不是"{}"类型的,而是"[]"类型的,那么以上的解析方式不适用,需要将
NSDictionary* dic = [jsonStr objectFromJSONString];
NSArray* array = [jsonStr objectFromJSONString];
这时获得的数组是JKDictionary类型,如下;
要想将array中的对象转换成自己的对象,需要再遍历一边数组,使用
BMClass* c = [[BMClass alloc]initWithDictionary:dic];
为每个对象进行转换即可。
=================================这是分割线=========================================
现在讲java如何实现:
java下需要用到一个包。
java下解析json利用gson比iOS下略简单,思路是获取到要解析的对象的Type,然后利用GSON提供的fromJson方法解析就好了。
沿用上边iOS的json字符串举例:
BMClass.class代码如下:
public class BMClass {
public List&BMStudent&
BMStudent.class代码如下:
public class BMStudent {
Object类型的json字符串转换为对象
解析的过程代码如下:
Gson gson = new Gson();
Type classType = new TypeToken&BMClass&() {}.getType();
BMClass c = gson.fromJson(jsonStr, classType);
解析的结果如下(Debug截图):
List类型的json字符串转换为对象
解析的地方只更换Type的类型即可,例如:
Type classType = new TypeToken&List&BMClass&&() {}.getType();
文章结束。
阅读(...) 评论()下次自动登录
现在的位置:
& 综合 & 正文
[C/OC的那点事儿]使用JSONKit进行JSON文件和NSString,NSArray,Dic NSData文件的相互转化
1.简单的JSONKit 包下的 转换
首先我们需要引入JSONKit.h,m文件.百度一下就能下载了.
//假如 str就是网络获取的json文件
NSString *str = [NSString stringWithFormat:@"{\"id\":1,\"age\":\"2\"}"];
NSDictionary *resultsDictionary = [str objectFromJSONString];//转化为字典类型的文件
NSLog(@"%@",resultsDictionary);
// insert code here...
NSLog(@"Hello, World!");
//dic文件转化为json文件
NSMutableDictionary *people = [NSMutableDictionary dictionary];
NSMutableDictionary *boy = [NSMutableDictionary dictionary];
NSMutableDictionary *girl= [NSMutableDictionary dictionary];
NSMutableDictionary *cat = [NSMutableDictionary dictionary];
NSMutableDictionary *pandon = [NSMutableDictionary dictionary];
NSMutableDictionary *mammalia = [NSMutableDictionary dictionary];//哺乳类
NSMutableDictionary *repilia = [NSMutableDictionary dictionary];//爬行类
NSMutableDictionary *animal = [NSMutableDictionary dictionary];//
[boy setObject:@"李蝉" forKey:@"lc"];
[boy setObject:@"赵明伟" forKey:@"zz"];
[girl setObject:@"李若" forKey:@"lr"];
[girl setObject:@"徐娜" forKey:@"xn"];
[people setObject:boy forKey:@"boy"];
[people setObject:girl forKey:@"girl"];
[pandon setObject:@"大熊猫" forKey:@"大pandon"];
[pandon setObject:@"小猫" forKey:@"小pandon"];
[cat setObject:pandon forKey:@"cat"];
[mammalia setObject:people forKey:@"people"];
[mammalia setObject:pandon forKey:@"pandon"];
[animal setObject:mammalia forKey:@"animal"];
[repilia setObject:@"pa虫" forKey:@"repilia"];
[animal setObject:repilia forKey:@"爬行类"];
NSString *string = [animal JSONString];
NSLog(@"%@",string);
11:34:51.692 JSON解析[] {
11:34:51.694 JSON解析[] Hello, World!
11:34:51.697 JSON解析[] {"爬行类":{"repilia":"pa虫"},"animal":{"pandon":{"大pandon":"大熊猫","小pandon":"小猫"},"people":{"boy":{"lc":"李蝉","zz":"赵明伟"},"girl":{"lr":"李若","xn":"徐娜"}}}}
Program ended with exit code: 0
* json格式编码
NSString *res =
NSString *str = @"this is a nsstring";
res = [str JSONString];
NSLog(@"res= %@", [NSString stringWithString: res]);
//res= "this is a nsstring"
NSArray *arr = [[NSArray alloc] initWithObjects:@"One",@"Two",@"Three",nil];
res = [arr JSONString];
NSLog(@"res= %@", [NSString stringWithString: res]);
[arr release];
//res= ["One","Two","Three"]
//字典类型(对象)
NSArray *arr1 = [NSArray arrayWithObjects:@"dog",@"cat",nil];
NSArray *arr2 = [NSArray arrayWithObjects:[NSNumber numberWithBool:YES],[NSNumber numberWithInt:30],nil];
NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:arr1,@"pets",arr2,@"other",nil];
res = [dic JSONString];
NSLog(@"res= %@", [NSString stringWithString: res]);
//res= {"pets":["dog","cat"],"other":[true,30]}
* json格式解码
JSONDecoder *jd=[[JSONDecoder alloc] init];
//针对NSData数据
NSData *data = [dic JSONData];
NSDictionary *ret = [jd objectWithData: data];
NSLog(@"res= %@", [ret objectForKey:@"pets"]);
NSLog(@"res= %@", [[ret objectForKey:@"other"] objectAtIndex:0]);
//针对NSString字符串数据
NSString *nstr = [dic JSONString];
NSDictionary *ret2 = [jd objectWithUTF8String:(const unsigned char *)[nstr UTF8String] length:(unsigned int)[nstr length]];
NSLog(@"res= %d", [[ret2 objectForKey:@"pets"] indexOfObject:@"cat"]);
NSLog(@"res= %@", [[ret2 objectForKey:@"other"] objectAtIndex:1]);
&&&&推荐文章:
【上篇】【下篇】Objective-C实现将URL参数转换为字典并封装成数组
代码首先我们得会一个字符串拆分函数 componentsSeparatedByString:@&&&,把字符串按照&进行拆分,然后返回字符串数组输入的数据的格式如下(装有url的字符串数组):(
&&&&&?a=10&b=20&,
&&&&&?a=10&b=20&c=30&,
&&&&&?a=10&c=30&
)主要代码:
NSMutableArray&*&dataArray()
&&&&//用来作为函数的返回值,数组里里面可以存放每个url转换的字典
&&&&NSMutableArray&*arrayData&=&[NSMutableArray&arrayWithCapacity:4];
&&&&//获取数组,数组里装得是url
&&&&NSMutableArray&*arrayURL&=&appendURL();
&&&&NSLog(@&获取到得URL数组如下:\n%@&,&arrayURL);
&&&&//循环对数组中的每个url进行处理,把参数转换为字典
&&&&for&(int&i&=&0;&i&&&arrayURL.&i&++)
&&&&&&&&NSLog(@&第%d个URL的处理过程:%@&,&i+1,&arrayURL[i]);
&&&&&&&&//获取问号的位置,问号后是参数列表
&&&&&&&&NSRange&range&=&[arrayURL[i]&rangeOfString:@&?&];
&&&&&&&&NSLog(@&参数列表开始的位置:%d&,&(int)range.location);
&&&&&&&&//获取参数列表
&&&&&&&&NSString&*propertys&=&[arrayURL[i]&substringFromIndex:(int)(range.location+1)];
&&&&&&&&NSLog(@&截取的参数列表:%@&,&propertys);
&&&&&&&&//进行字符串的拆分,通过&来拆分,把每个参数分开
&&&&&&&&NSArray&*subArray&=&[propertys&componentsSeparatedByString:@&&&];
&&&&&&&&NSLog(@&把每个参数列表进行拆分,返回为数组:\n%@&,&subArray);
&&&&&&&&//把subArray转换为字典
&&&&&&&&//tempDic中存放一个URL中转换的键值对
&&&&&&&&NSMutableDictionary&*tempDic&=&[NSMutableDictionary&dictionaryWithCapacity:4];
&&&&&&&&for&(int&j&=&0&;&j&&&subArray.&j++)
&&&&&&&&&&&&//在通过=拆分键和值
&&&&&&&&&&&&NSArray&*dicArray&=&[subArray[j]&componentsSeparatedByString:@&=&];
&&&&&&&&&&&&NSLog(@&再把每个参数通过=号进行拆分:\n%@&,&dicArray);
&&&&&&&&&&&&//给字典加入元素
&&&&&&&&&&&&[tempDic&setObject:dicArray[1]&forKey:dicArray[0]];
&&&&&&&&NSLog(@&打印参数列表生成的字典:\n%@&,&tempDic);
&&&&&&&&[arrayData&addObject:tempDic];
&&&&NSLog(@&打印参数字典生成的数组:\n%@&,&arrayData);
&&&&return&arrayD
}说明1.先把参数列表在url中的参数列表的起始位置获取到,通过方法rangeOfString方法获取2.位置获取到以后我们可以把参数列表从url字符串中提取出来,通过substringFromIndex来获取。3.通过componentsSeparatedByString把参数列表进行每项的拆分4.通过componentsSeparatedByString把每项进行键值对的拆分5.把键值对存入字典6.把字典存入数组(ios)字符串与数组,字典,对象之间的转换 - 简书
(ios)字符串与数组,字典,对象之间的转换
app开发过程中,与服务器数据交流时,服务器常常需要我们把一些集合以字符串的方式传给服务器,下面就是一些字符串和数组,字典,对象之间的转换。
判断自己是否为空
@return &#return value description#&
- (BOOL) isBlank
if (!self.length ||
self == nil ||
self == NULL ||
(NSNull *)self == [NSNull null] ||
[self isKindOfClass:[NSNull class]] ||
[self isEqualToString:@"(null)"] ||
[self isEqualToString:@"&null&"] ||
[self isEqualToString:@"null"] ||
[self isEqualToString:@"NULL"]
return YES;
return NO;
json字符串,转成字典
字符串调用
@return &#return value description#&
- (NSDictionary *)stringJsonToDictionary{
if ([self isBlank]) {
NSData *jsonData = [self dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:err];
NSLog(@"json解析失败:%@",err);
字典转json字符串
@return &#return value description#&
- (NSString *)dictionaryToJsonString{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self
options:NSJSONWritingPrettyPrinted
error:nil];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
数组转json字符串
@return &#return value description#&
- (NSString *)arrayToJsonString{
NSError *parseError =
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&parseError];
return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
对象转换为字典
@param obj 需要转化的对象
@return 转换后的字典
+ (NSDictionary*)getObjectData:(id)obj {
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
unsigned int propsC
objc_property_t *props = class_copyPropertyList([obj class], &propsCount);
for(int i = 0;i & propsC i++) {
objc_property_t prop = props[i];
NSString *propName = [NSString stringWithUTF8String:property_getName(prop)];
id value = [obj valueForKey:propName];
if(value == nil) {
value = [NSNull null];
value = [self getObjectInternal:value];
[dic setObject:value forKey:propName];
+ (id)getObjectInternal:(id)obj {
if([obj isKindOfClass:[NSString class]]
[obj isKindOfClass:[NSNumber class]]
[obj isKindOfClass:[NSNull class]]) {
if([obj isKindOfClass:[NSArray class]]) {
NSArray *objarr =
NSMutableArray *arr = [NSMutableArray arrayWithCapacity:objarr.count];
for(int i = 0; i & objarr. i++) {
[arr setObject:[self getObjectInternal:[objarr objectAtIndex:i]] atIndexedSubscript:i];
if([obj isKindOfClass:[NSDictionary class]]) {
NSDictionary *objdic =
NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:[objdic count]];
for(NSString *key in objdic.allKeys) {
[dic setObject:[self getObjectInternal:[objdic objectForKey:key]] forKey:key];
return [self getObjectData:obj];

我要回帖

更多关于 将数组中的数逆序存放 的文章

 

随机推荐