JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一个子集。 JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成(网络传输速度快)。
@interface Json : NSObject
@property(nonatomic, retain)NSMutableArray *array;
@property(nonatomic,retain)NSMutableDictionary *dic;
// 提供的外部接口,根据第一层是数组还是字典来调用不同的方法
- (NSMutableArray *)jsonParser:(NSString *)name type:(NSString *)type;
- (NSMutableDictionary *)jsonParserDic:(NSString *)name type:(NSString *)type;
@end
Json.m
@implementation Json
- (void)dealloc
{
[_dic release];
[_array release];
[super dealloc];
}
- (instancetype)init
{
self = [super init];
if (self) {
// 初始化中对数组和字典这种容器进行初始化
self.array = [NSMutableArray array];
self.dic = [NSMutableDictionary dictionary];
}
return self;
}
- (NSMutableArray *)jsonParser:(NSString *)name type:(NSString *)type;
{
// 提取路径
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:type];
// 根据路径提取数据
NSData *data = [NSData dataWithContentsOfFile:path];
// 将解析完的数据付给数组
self.array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
return self.array;
}
- (NSMutableDictionary *)jsonParserDic:(NSString *)name type:(NSString *)type
{
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:type];
NSData *data = [NSData dataWithContentsOfFile:path];
// 将解析完的数据付给字典
self.dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
return self.dic;
}
@end