json数据:
[html] view plaincopy
- {
- "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文件路径,根据路径来获取里面的数据:
[html] view plaincopy
- NSString *path=[[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"];
- NSString *_jsonContent=[[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
2、然后根据得到的_jsonContent字符串对象来获取里面的键值对:
[html] view plaincopy
- NSMutableDictionary dict=[_jsonContent JSONValue];//我们不需要去定义获取的方法,使用系统定义好的JSONValue即可
3、然后根据得到的键值对来进行JSON解析:
[java] view plaincopy
- //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"];
- }
这样就可以实现解析json数据了。。。
时间: 2024-10-10 00:38:28