json样例如下
{
"result": [
{
"meeting": {
"addr": "203",
"creator": "张一",
"member": [
{
"name": "张二",
"age": "20"
},
{
"name": "张三",
"age": "21"
},
{
"name": "张四",
"age": "22"
}
]
}
},
{
"meeting": {
"addr": "204",
"creator": "张二",
"member": [
{
"name": "张二",
"age": "20"
},
{
"name": "张三",
"age": "21"
},
{
"name": "张四",
"age": "22"
}
]
}
}
]
}
1、获取json文件路径,根据路径来获取里面的数据:
NSString *path=[[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"];
NSString *_jsonContent=[[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
2、然后根据得到的_jsonContent字符串对象来获取里面的键值对:
NSMutableDictionary dict=[_jsonContent JSONValue];//我们不需要去定义获取的方法,使用系统定义好的JSONValue即可
3、然后根据得到的键值对来进行JSON解析:
/*
根据上面json数据之间的逻辑关系,可以获知我们解析的顺序:
1. 根据得到的字符串获取里面的键值对,
2. 根据得到的键值对通过key来得到对应的值,也就是值里面的数组,
3. 然后获取数组中的键值对,
4. 然后根据得到的键值对通过key获取里面的键值对中的值
*/
//json解析
//2.
NSArray *result=[_dict objectForKey:@"result"];
//3.
NSDictionary *dic=[result objectAtIndex:0];
//4.
NSDictionary *meeting=[dic
objectForKey:@"meeting"];
//得到 addr 值
NSString *address = [meeting objectForKey:@"addr"];
//得到 creator 值
NSString *creator = [meeting objectForKey:@"creator"];
//得到 member 里面的数据,因为这个键值中有数组,所以要重复上面的2,3,4的动作
//2.
NSArray *members=[meeting objectForKey:@"member"];
//3.
//这里用了for循环语句,
for (NSDictionary * member in members) {
//4.
NSString *name = [member objectForKey:@"name"];
NSString *age = [member objectForKey:@"age"];
}