1.简单粗暴直接上代码
----------------------------------
#import "ViewController.h"
#import "MessageModel.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self demo];
}
- (void)demo {
// 1. url
NSURL *url = [NSURL URLWithString:@"http://192.168.43.32/myWeb/demo.json"];
// 2. 请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 3. 发起请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
// 4. 处理数据
if (connectionError != nil || data.length == 0) {
NSLog(@"请求错误! %@", connectionError);
return;
}
// 二进制数据能够直接显示到界面上吗?
// 应该将其反序列化成OC的对象
// 如果反序列化出错,就会把错误信息保存到该 NSError 中
NSError *error;
/**
// 可变的容器: 解析出来的容器是否是可变的 Mutable
NSJSONReadingMutableContainers = (1UL << 0),
// 可变的叶子节点 iOS 7 之后就不知道什么原因,不可用了. stackoverflow (程序员的问答社区,全英文)
NSJSONReadingMutableLeaves = (1UL << 1),
// 允许不是正确的JSON反序化
NSJSONReadingAllowFragments = (1UL << 2)
*/
id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
// NSLog(@"%@", error);
//将解析的JSON数据传值给模型
MessageModel *model = [MessageModel messageWithDict:result];
//输出模型信息
NSLog(@"%@", model);
// 只有将二进制数据转成OC中的对象,才能取数据
// NSString *msg = result[@"message"];
// NSLog(@"msg = %@", msg);
NSLog(@"%@ %@",result, [result class]);
}];
}
@end
2.自定义的模型:
----------------------------------
#import <Foundation/Foundation.h>
@interface MessageModel : NSObject
/**
* 消息Id
* NSNumber 是 基本数据类型 int double float 的包装类型
* NSValue 是 结构体的包装类型
*/
@property (nonatomic, strong) NSNumber *messageId;
/**
* 消息内容
*/
@property (nonatomic, copy) NSString *message;
/**
* 字典转模型的构造方法
*
* @param dict <#dict description#>
*
* @return <#return value description#>
*/
+ (instancetype)messageWithDict:(NSDictionary *)dict;
@end
----------------------------------
#import "MessageModel.h"
@implementation MessageModel
+ (instancetype)messageWithDict:(NSDictionary *)dict{
// NSValue : NSRange CGRect
// 1. 初始化一个模型
MessageModel *model = [[MessageModel alloc] init];
// 2. 设置模型中的属性
[model setValuesForKeysWithDictionary:dict];
return model;
}
// 如果不重写,就会打印对象的地址,地址对我们没有帮助,所以重写这个方法,返回我们想看到的东西
// NSLog 的时候,会调用对象的 description 方法去获取打印的内容
- (NSString *)description {
// dictionaryWithValuesForKeys 会去取key对应的值转成一个字典返回,而我们只需要打印字典的 description 就可以看到内容
return [[self dictionaryWithValuesForKeys:@[@"message", @"messageId"]] description];
// return [NSString stringWithFormat:@"messageId = %@, message = %@", _messageId, _message];
}
@end