解析思路
1.获取数据来源,就是文件的保存路径 NSString *path。调用方法:pathForResource
2.读取文件数据,把path转换成NSData *data。调用方法:[NSData dataWtihContentsOffFile:path];
3.解析文件数据(获取key对应的value),接收原则:{}使用字典;[]使用数组。调用方法:[NSJSONSerialization JSONObjectWithData:]
DOMO
解析文件 test.json
{
"FeelsLikeC" : 5,
"temp_c" : "3",
"request" : [ { "query" : "Beijing,China" } ]
}
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//数据来源(test.json)
//读取文件数据
NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"test.json" ofType:nil];
NSData *jsonData = [NSData dataWithContentsOfFile:jsonPath];
//解析(获取key对应的value)
//接收原则:{}使用字典;[]使用数组
NSError *error = nil;
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
//体感温度
NSNumber *feelsTemp = jsonDic[@"FeelsLikeC"];
//预报天气的温度
NSString *temp = jsonDic[@"temp_c"];
//城市名字
NSArray *requestArray = jsonDic[@"request"];
NSDictionary *queryDic = requestArray[0];
NSString *cityStr = queryDic[@"query"];
//验证
NSLog(@"feelsTemp:%@; temp:%@; cityStr:%@", feelsTemp, temp, cityStr);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
网友评论