我的SBJson来生成和解析JSON串的代码

前端之家收集整理的这篇文章主要介绍了我的SBJson来生成和解析JSON串的代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

一、OC里生成指定格式JSON串的关键秘诀为:

①、每个{} 对应一个 NSDictionary

②、每个[] 对应一个 NSArray


二、代码如下:

#import "ViewController.h"

#import "SBJson.h"


@interface ViewController ()

{

NSString *strMyJson;

}


@end


@implementation ViewController


- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view,typically from a nib.

//生成一个JSON

if (![self writeJson])

{

NSLog(@"写出JSON字符串失败");

return;

}

else

NSLog(@"写出JSON字符串成功");

//解析一个JSON

if (![self readJson])

{

NSLog(@"解析JSON字符串失败");

return;

}

else

NSLog(@"解析JSON字符串成功");

}


-(BOOL) readJson

{

@try

{

SBJsonParser *parser=[[SBJsonParser alloc] init];

NSDictionary *dic3_1=[parser objectWithString:strMyJson];

if (nil!=dic3_1)

{

NSLog(@"%@",dic3_1.allKeys[0]);

NSDictionary *dic2_1=dic3_1.allValues[0];

NSLog(@"%@",dic2_1.allKeys[0]);

NSLog(@"%@",dic2_1.allKeys[1]);

NSDictionary *dic1=dic2_1.allValues[0];

NSDictionary *dic2=dic2_1.allValues[1];

NSLog(@"%@",dic1.allKeys[0]);

NSLog(@"%@",dic1.allValues[0]);

NSLog(@"%@",dic1.allKeys[1]);

NSLog(@"%@",dic1.allValues[1]);

NSLog(@"%@",dic2.allKeys[0]);

NSLog(@"%@",dic2.allValues[0]);

NSLog(@"%@",dic2.allKeys[1]);

NSLog(@"%@",dic2.allValues[1]);

return YES;

}

else

{

return NO;

}

}

@catch (NSException *exception)

{

return NO;

}

}


-(BOOL) writeJson

{

@try

{

NSDictionary *dic1=[NSDictionary dictionaryWithObjectsAndKeys:@"8888",@"age",@"174",@"length",nil];

NSDictionary *dic2=[NSDictionary dictionaryWithObjectsAndKeys:@"9999",@"178",nil];

NSDictionary *dic2_1=[NSDictionary dictionaryWithObjectsAndKeys:dic1,@"liji",dic2,@"lixi",nil];

NSDictionary *dic3_1=[NSDictionary dictionaryWithObjectsAndKeys:dic2_1,@"person",nil];

SBJsonWriter *writer=[[SBJsonWriter alloc] init];

NSString *strJson=[writer stringWithObject:dic3_1];

if (nil!=strJson)

{

strMyJson=strJson;

NSLog(@"%@",strJson);

return YES;

}

else

return NO;


}

@catch(NSException *e)

{

return NO;

}

}




- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}


@end

猜你在找的Json相关文章