天天看點

Json本地解析

- (void)viewDidLoad {
    [super viewDidLoad];

    //1.擷取檔案的路徑
    NSString *jsonFilePath = [[NSBundle mainBundle] pathForResource:@"test.json" ofType:nil];
    //2.讀取檔案内的資料(NSData類型:一般伺服器傳回的資料類型是NSData)
    NSData *jsonData = [NSData dataWithContentsOfFile:jsonFilePath];
    //3.JSON解析
    /* 流程:JSON對象轉Foundation對象
       使用什麼類型的Foundation對象的原則: 最外層是中括号/數組,使用NSArray;最外層是大括号/對象,使用NSDictionary
     */
    NSError *error = nil;
    NSDictionary *dicFromFile = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
    //4.取值并驗證解析的資料
    /* 取值原則:從外往裡一層一層
     */
    NSNumber *feelsLikeC  = dicFromFile[@"FeelsLikeC"];
    NSString *tempC       = dicFromFile[@"TempC"];
    NSArray *requestArray = dicFromFile[@"Request"];
    NSDictionary *cityDic = requestArray[];
    NSString *cityName    = cityDic[@"city"];
    NSDictionary *locationDic = requestArray[];
    NSString *locationStr = locationDic[@"location"];
    NSNumber *count = dicFromFile[@"Paging"][@"count"];

    NSLog(@"體感溫度:%@;天氣溫度:%@;城市名字:%@;區域名字:%@;頁數:%@",feelsLikeC, tempC, cityName, locationStr,count);
}