码迷,mamicode.com
首页 > Web开发 > 详细

parse Json

时间:2015-12-18 00:05:57      阅读:310      评论:0      收藏:0      [点我收藏+]

标签:

一、数据来源

1.来源于mainBundle

2.来源于服务器

二、解析步骤

`1.数据来源于mainBundle

//读取数据

    NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"test.json" ofType:nil];
解析数据(获取key对应的value)接受原则,{}使用字典 []是用数组接受

  NSError *error = nil;
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
//如果有错误可以打印

If(error){

NSLog(_@”%@”,error.userInfo);

 

}

//体感温度
    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);
特殊标注的是重点掌握

 

2.服务器解析 parseJson –server

因为要与服务器相应,所以就要发送网络请求

//发送请求  

 NSURLRequest * request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.raywenderlich.com/demos/weather_sample/weather.php?format=json"]];
//创建NSURLSession的实例4对象(感觉像是一种媒介)

脑补一下:NSURLSession

 

NSURLSession提供的功能:

1.通过URL将数据下载到内存

2.通过URL将数据下载到文件系统

3.将数据上传到指定URL

4.在后台完成上述功能

 

  NSURLSession *session = [NSURLSession sharedSession];

//创建任务    其中block中的线程是子线程

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
        if (statusCode == 200) {
            //NSData --> JSON Object(NSDictionary/NSArray)
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            //解析jsonDic对应值
            [self parseJson:jsonDic];
        }
    }];
//开始任务

[task resume];

 

- (void)parseJson:(NSDictionary *)jsonDic {
    //解析(子线程)
    //湿度
    NSDictionary *dataDic = jsonDic[@"data"];
    NSArray *currentArray = dataDic[@"current_condition"];
    NSDictionary *currentDic = currentArray[0];
    NSString *humidityStr = currentDic[@"humidity"];
    //天气描述
    NSString *weatherDesc = dataDic[@"weather"][0][@"weatherDesc"][0][@"value"];
   
    //验证
    NSLog(@"humidity:%@; weatherDesc:%@", humidityStr, weatherDesc);
}
 

 

 

解析最重要的不是怎么得到数据,而是怎么建立数据模型,将庞大繁琐的解析工作剥离控制器,解析单独在一个类里完成。降低主控制器的工作种类,更加清晰的管理代码,下面是两个例子,一步步的将数据的解析独立起来

 

 

 

Demo-01

 

 

//  TRWeather.m
//  Demo02-JSONParse-Server
//  TRWeather.h
//  Demo02-JSONParse-Server
//
//  Created by tarena on 15/12/12.
//  Copyright © 2015年 tarena. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface TRWeather : NSObject
//湿度
@property (nonatomic, strong) NSString *humidity;
//天气描述
@property (nonatomic, strong) NSString *weatherDesc;

//给定自定参数,返回id(类方法/实例方法)
+ (id)parseJsonByModel:(NSDictionary *)jsonDic;
 

 

//  Created by tarena on 15/12/12.
//  Copyright © 2015年 tarena. All rights reserved.
//

#import "TRWeather.h"

@implementation TRWeather

+ (id)parseJsonByModel:(NSDictionary *)jsonDic {
    return [[self alloc] initWithJson:jsonDic];
}

- (id)initWithJson:(NSDictionary *)jsonDic {
    //解析逻辑
    if (self = [super init]) {
        self.humidity = jsonDic[@"data"][@"current_condition"][0][@"humidity"];
        //天气描述
    }
    return self;
}
 

 

 

//  ViewController.m
//  Demo02-JSONParse-Server
//
//  Created by tarena on 15/12/12.
//  Copyright © 2015年 tarena. All rights reserved.
//

#import "ViewController.h"
#import "TRWeather.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    //发送请求
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.raywenderlich.com/demos/weather_sample/weather.php?format=json"]];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
        if (statusCode == 200) {
            //NSData --> JSON Object(NSDictionary/NSArray)
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            //解析jsonDic对应值
            [self parseJson:jsonDic];
        }
    }];
    [task resume];
    //接收服务器返回的数据
}

- (void)parseJson:(NSDictionary *)jsonDic {
    //解析(子线程)
    TRWeather *weather = [TRWeather parseJsonByModel:jsonDic];
    //验证
    NSLog(@"humidity:%@", weather.humidity);
}

 

 

Demo 2

//  TRDaily.h
//  Demo02-JSONParse-Server
//
//  Created by tarena on 15/12/12.
//  Copyright © 2015年 tarena. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface TRDaily : NSObject
//最高温
@property (nonatomic, strong) NSString *tempMaxC;
//最低温
@property (nonatomic, strong) NSString *tempMinC;
//天气图标的url
@property (nonatomic, strong) NSString *iconURL;

//给定字典参数,返回id
+ (id)parseJsonByDic:(NSDictionary *)weatherDic;


 

//
//  TRDaily.m
//  Demo02-JSONParse-Server
//
//  Created by tarena on 15/12/12.
//  Copyright © 2015年 tarena. All rights reserved.
//

#import "TRDaily.h"

@implementation TRDaily

+ (id)parseJsonByDic:(NSDictionary *)weatherDic {
    return [[self alloc] initWithJsonDic:weatherDic];
}

- (id)initWithJsonDic:(NSDictionary *)weatherDic {
    if (self = [super init]) {
        //最高温
        self.tempMaxC = weatherDic[@"tempMaxC"];
        //最低温
        self.tempMinC = weatherDic[@"tempMinC"];
        //图片url的value
        self.iconURL = weatherDic[@"weatherIconUrl"][0][@"value"];
    }
    return self;
}

@end
 

 

 

//  TRDataManager.h
//  Demo02-JSONParse-Server
//
//  Created by tarena on 15/12/12.
//  Copyright © 2015年 tarena. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface TRDataManager : NSObject


//给定字典,返回已经解析好得TRDaily模型对象组成的数组
+ (NSArray *)parseWeatherArray:(NSDictionary *)jsonDic;


@end
 

 

//  TRDataManager.m
//  Demo02-JSONParse-Server
//
//  Created by tarena on 15/12/12.
//  Copyright © 2015年 tarena. All rights reserved.
//

#import "TRDataManager.h"
#import "TRDaily.h"

@implementation TRDataManager

+ (NSArray *)parseWeatherArray:(NSDictionary *)jsonDic {
    NSArray *weatherArray = jsonDic[@"data"][@"weather"];
    //声明可变数组(存储已经转完的模型对象)
    NSMutableArray *mutableArray = [NSMutableArray array];
    for (NSDictionary *weatherDic in weatherArray) {
        //weatherDic -> TRDaily
        TRDaily *daily = [TRDaily parseJsonByDic:weatherDic];
        [mutableArray addObject:daily];
    }
   
    return [mutableArray copy];
}

@end
 

 

 

//
//  TRWeather.h
//  Demo02-JSONParse-Server
//
//  Created by tarena on 15/12/12.
//  Copyright © 2015年 tarena. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface TRWeather : NSObject
//湿度
@property (nonatomic, strong) NSString *humidity;
//天气描述
@property (nonatomic, strong) NSString *weatherDesc;

//给定自定参数,返回id(类方法/实例方法)
+ (id)parseJsonByModel:(NSDictionary *)jsonDic;

@end
 

 

 

//
//  TRWeather.m
//  Demo02-JSONParse-Server
//
//  Created by tarena on 15/12/12.
//  Copyright © 2015年 tarena. All rights reserved.
//

#import "TRWeather.h"

@implementation TRWeather

+ (id)parseJsonByModel:(NSDictionary *)jsonDic {
    return [[self alloc] initWithJson:jsonDic];
}

- (id)initWithJson:(NSDictionary *)jsonDic {
    //解析逻辑
    if (self = [super init]) {
        self.humidity = jsonDic[@"data"][@"current_condition"][0][@"humidity"];
        //天气描述
    }
    return self;
}

@end
 

 

 

//
//  ViewController.m
//  Demo02-JSONParse-Server
//
//  Created by tarena on 15/12/12.
//  Copyright © 2015年 tarena. All rights reserved.
//

#import "ViewController.h"
#import "TRWeather.h"
#import "TRDaily.h"
#import "TRDataManager.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    //发送请求
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.raywenderlich.com/demos/weather_sample/weather.php?format=json"]];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
        if (statusCode == 200) {
            //NSData --> JSON Object(NSDictionary/NSArray)
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            //解析jsonDic对应值
            [self parseJson:jsonDic];
        }
    }];
    [task resume];
    //接收服务器返回的数据
}

- (void)parseJson:(NSDictionary *)jsonDic {
    //第一种情况: 字典 ---> TRWeather
    //解析(子线程)
    TRWeather *weather = [TRWeather parseJsonByModel:jsonDic];
    //验证
    NSLog(@"humidity:%@", weather.humidity);
   
    //第二种情况: 数组(字典,字典....) ---> 数组(TRDaily,TRDaily....)
    NSArray *weatherArray = jsonDic[@"data"][@"weather"];
    //声明可变数组(存储已经转完的模型对象)
    NSMutableArray *mutableArray = [NSMutableArray array];
    for (NSDictionary *weatherDic in weatherArray) {
        //weatherDic -> TRDaily
        TRDaily *daily = [TRDaily parseJsonByDic:weatherDic];
        [mutableArray addObject:daily];
    }
   
    //验证(mutableArray)
    for (TRDaily *daily in mutableArray) {
        NSLog(@"maxC:%@; minC:%@; url:%@", daily.tempMaxC, daily.tempMinC, daily.iconURL);
    }
   
    //第三种情况: 将控制器中的循环解析封装到TRDataManager中
    NSArray *array = [TRDataManager parseWeatherArray:jsonDic];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
 

 

parse Json

标签:

原文地址:http://www.cnblogs.com/zhao-jie-li/p/PraseJson.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!