JSON解析
1.实质
将返回的数据放入模型(model)中 json(相对于xml的数据,轻巧,传输速率高,冗余的数据少。缺点:可读性差些)
xml(冗余的数据多,优点:可读性强,扩展性强)
2.解析步骤
(1)查看解析文档,建立模型类
模型类头文件AppDetailModel.h
#import <Foundation/Foundation.h>
@interface AppDetailModel : NSObject
//生成模型类的属性—----由于数据量比较大,不能一个一个属性添加。
//点击Window,选择ESJsonFormat,选择input Json window,然后将要解析的文档内容拷贝进来,点击enter在输入框对数组属性加一个Model后缀。点击enter。会自动生成所有的对应属性。
//注意:若有discription属性,需要对该属性改名。
@end
模型类实现文件AppDetailModel.m
#import "AppDetailModel.h"
@implementation AppDetailModel
//将多余的其他方法删除
//需要对该方法实现,可不写具体实现。
- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
}
@end
//下面的是自动生成的
@implementation PhotosModel
@end
3.解析数据
* Json解析式OC中自带,由官方提供的
*
*/
//Json数据转换为字典-------id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
//字典或者数组转换为Json数据--------NSData *jsonWriteData = [NSJSONSerialization dataWithJSONObject:colorDic options:NSJSONWritingPrettyPrinted error:&error];
#import <Foundation/Foundation.h>
#import "AppDetailModel.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//读取Json文件内容
NSData *data = [NSData dataWithContentsOfFile:@"/Users/IOS1602/Desktop/OC第10天/JSON数据/App详情.json"];
//NSLog(@"%@",data);
//通过OC中自带的Json解析器解析Json文本数据
//参数1:要解析的Json数据
//参数2:枚举类型--确定Json数据解析后的格式
// NSJSONReadingMutableContainers
// NSJSONReadingMutableLeaves
// NSJSONReadingAllowFragments
NSError *error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];//返回的是一个字典
// NSString *name = [jsonObject objectForKey:@"name"];
// NSLog(@"%@",name);
// NSArray *arr = [jsonObject objectForKey:@"photos"];
// for (NSDictionary *dic in arr) {
// NSLog(@"%@",dic);
// }
//遍历jsonObject字典
NSDictionary *jsonDic = jsonObject;
for (NSString *key in jsonDic.allKeys) {
NSLog(@"%@",[jsonDic valueForKey:key]);
}
/**
* 将字典或者数组转换为Json数据(带大括号、中括号的格式的数据)
*/
NSDictionary *colorDic = @{@"red":@"红",@"blue":@"蓝",@"yellow":@"黄"};
//通过Json序列化将字典或者数组转换成Json数据
NSData *jsonWriteData = [NSJSONSerialization dataWithJSONObject:colorDic options:NSJSONWritingPrettyPrinted error:&error];
//将二进制数据转换为字符串
NSString *writeStr = [[NSString alloc]initWithData:jsonWriteData encoding:NSUTF8StringEncoding];
NSLog(@"%@",writeStr);
/**
* 将字典数据转换为类对象
*/
AppDetailModel *detailModel = [[AppDetailModel alloc] init];
//将字典中的数据赋值给类对象的属性
//KVC (key-value Coding)
[detailModel setValuesForKeysWithDictionary:jsonDic];
NSLog(@"model name = %@",detailModel.name);
}
return 0;
}