一、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
原文链接:https://www.f2er.com/json/289599.html