JSONModel源码阅读笔记
JSONModel是一个解析服务器返回的Json数据的库。
http://blog.csdn.net/dyllove98/article/details/9050905
通常服务器传回的json数据要通过写一个数据转换模块将NSDictionary转换为Model,将NSString数据转换为Model中property的数据类型。
这样服务器如果要做修改,可能需要改两三个文件。
JSONModel的出现就是为了将这种解析工作在设计层面完成。
使用方法:参考连接
对其源码的核心部分JSONModel.m做了源码阅读,笔记如下:
在
-(id)initWithDictionary:(NSDictionary*)dict error:(NSError**)err
函数中完成所有解析工作:如果有任何失误或者错误直接返回nil。
-(id)initWithDictionary:(NSDictionary*)dict error:(NSError**)err
{
//1、做有效性判断(dict是不是空啊,dict是不是真是一个NSDictionary)
//check for nil input
if (!dict) {
if (err) *err = [JSONModelError errorInputIsNil];
return nil;
} //invalid input, just create empty instance
if (![dict isKindOfClass:[NSDictionary class]]) {
if (err) *err = [JSONModelError errorInvalidData];
return nil;
} //create a class instance
self = [super init];
if (!self) { //super init didn't succeed
if (err) *err = [JSONModelError errorModelIsInvalid];
return nil;
} //__setup__中通过调用__restrospectProperties建立类属性的映射表,并且存放在全局变量classProperties里面
//->__restrospectProperties中利用runtime function搞出属性列表:
// ->获得属性列表class_copyPropertyList(得到objc_property_t数组)->对于每一个objc_property_t调用property_getName获得名称,property_getAttributes获得属性的描述(字符串)->通过解析字符串获得属性的类型、是否是Mutable、是否是基本的JSON类型等等
// ->调用[class superclass]获得父类继续获取列表
// ->列表保存在classProperties中备用
//->调用+keyMapper获得key转换列表,生成JSONKeyMapper对象存入keyMapper。
//do initial class setup, retrospec properties
[self __setup__]; //看看必传参数中是否在输入参数中都有。
//check if all required properties are present
NSArray* incomingKeysArray = [dict allKeys];
NSMutableSet* requiredProperties = [self __requiredPropertyNames];
NSSet* incomingKeys = [NSSet setWithArray: incomingKeysArray]; //get the key mapper
JSONKeyMapper* keyMapper = keyMappers[__className_]; //transform the key names, if neccessary
if (keyMapper) {
//对比dict输入的keyName导入NSSet与keyMapper中JSONKeyMapper对象做keyName的转换。统一转换为对象的propertyname。
NSMutableSet* transformedIncomingKeys = [NSMutableSet setWithCapacity: requiredProperties.count];
NSString* transformedName = nil; //loop over the required properties list
for (NSString* requiredPropertyName in requiredProperties) { //get the mapped key path
transformedName = keyMapper.modelToJSONKeyBlock(requiredPropertyName); //chek if exists and if so, add to incoming keys
if ([dict valueForKeyPath:transformedName]) {
[transformedIncomingKeys addObject: requiredPropertyName];
}
} //overwrite the raw incoming list with the mapped key names
incomingKeys = transformedIncomingKeys;
} //利用NSSet的isSubsetOfSet:将必传参数表与输入的keyName表对比。如果不是包含关系说明参数传的不够。
//check for missing input keys
if (![requiredProperties isSubsetOfSet:incomingKeys]) { //get a list of the missing properties
[requiredProperties minusSet:incomingKeys]; //not all required properties are in - invalid input
JMLog(@"Incoming data was invalid [%@ initWithDictionary:]. Keys missing: %@", self._className_, requiredProperties); if (err) *err = [JSONModelError errorInvalidDataWithMissingKeys:requiredProperties];
return nil;
} //not needed anymore
incomingKeys= nil;
requiredProperties= nil; //从对象的classProperties列表中循环到dict中取值:(赋值使用KVO操作的setValue:forKey:来做的,这样会直接调用setter函数赋值)
//loop over the incoming keys and set self's properties
for (JSONModelClassProperty* property in [self __properties__]) {
//对于每一个对象的property,通过keyMapper的转换找到对应dict property的dictKeyPath,找到值jsonValue。如果没有值,并且这个属性是Optional的就进行下一项property对比。
//convert key name ot model keys, if a mapper is provided
NSString* jsonKeyPath = property.name; if (keyMapper) jsonKeyPath = keyMapper.modelToJSONKeyBlock( property.name ); //JMLog(@"keyPath: %@", jsonKeyPath); //general check for data type compliance
id jsonValue = [dict valueForKeyPath: jsonKeyPath]; //check for Optional properties
if (jsonValue==nil && property.isOptional==YES) {
//skip this property, continue with next property
continue;
} //对找到的值做类型判断,如果不是JSON应该返回的数据类型就报错。(注意:NSNull是可以作为参数回传的)
Class jsonValueClass = [jsonValue class];
BOOL isValueOfAllowedType = NO; for (Class allowedType in allowedJSONTypes) {
if ( [jsonValueClass isSubclassOfClass: allowedType] ) {
isValueOfAllowedType = YES;
break;
}
} if (isValueOfAllowedType==NO) {
//type not allowed
JMLog(@"Type %@ is not allowed in JSON.", NSStringFromClass(jsonValueClass)); if (err) *err = [JSONModelError errorInvalidData];
return nil;
} //check if there's matching property in the model
//JSONModelClassProperty* property = classProperties[self.className][key]; //接着对property的属性与jsonValue进行类型匹配:
if (property) { //如果是基本类型(int/float等)直接值拷贝;
// 0) handle primitives
if (property.type == nil && property.structName==nil) { //just copy the value
[self setValue:jsonValue forKey: property.name]; //skip directly to the next key
continue;
} //如果是NSNull直接赋空值;
// 0.5) handle nils
if (isNull(jsonValue)) {
[self setValue:nil forKey: property.name];
continue;
} //如果是值也是一个JsonModel,递归搞JsonModel
// 1) check if property is itself a JSONModel
if ([[property.type class] isSubclassOfClass:[JSONModel class]]) { //initialize the property's model, store it
NSError* initError = nil;
id value = [[property.type alloc] initWithDictionary: jsonValue error:&initError]; if (!value) {
if (initError && err) *err = [JSONModelError errorInvalidData];
return nil;
}
[self setValue:value forKey: property.name]; //for clarity, does the same without continue
continue; } else { //如果property中有protocol解析将jsonValue按照protocol解析,如NSArray<JsonModelSubclass>,protocol就是JsonModelSubclass
// 2) check if there's a protocol to the property
// ) might or not be the case there's a built in transofrm for it
if (property.protocol) { //JMLog(@"proto: %@", p.protocol); //__transform:forProperty:函数功能:
// ->先判断下protocolClass是否在运行环境中存在,如不存在并且property是NSArray类型,直接报错。否则,直接返回。
// ->如果protocalClass是JsonModel的子类,
// ->如果property.type是NSArray
// ->判断一下是否是使用时转换
// ->如果为使用时转换则输出一个JSONModelArray(NSArray)的子类
// ->如果不是使用时转换则输出一个NSArray,其中的对象全部转换为protocalClass所对应对象
// ->如果property.type是NSDictionary
// ->将value转换为protocalClass所对应对象
// ->根据key存储到一个NSDictionary中输出
jsonValue = [self __transform:jsonValue forProperty:property];
if (!jsonValue) {
if (err) *err = [JSONModelError errorInvalidData];
return nil;
}
} //如果是基本JSON类型(NSString/NSNumber)
// 3.1) handle matching standard JSON types
if (property.isStandardJSONType && [jsonValue isKindOfClass: property.type]) { //如果是mutable的,做一份MutableCopy
//mutable properties
if (property.isMutable) {
jsonValue = [jsonValue mutableCopy];
} //set the property value
[self setValue:jsonValue forKey: property.name];
continue;
} //如果property.type是NSArray
// 3.3) handle values to transform
if (
//如果(类型没有匹配,并且jsonValue不为空)或者是Mutable的property(说明是特殊类型转换)
(![jsonValue isKindOfClass:property.type] && !isNull(jsonValue))
||
//the property is mutable
property.isMutable
) { //利用JSONValueTransformer找到源类型
// searched around the web how to do this better
// but did not find any solution, maybe that's the best idea? (hardly)
Class sourceClass = [JSONValueTransformer classByResolvingClusterClasses:[jsonValue class]]; //JMLog(@"to type: [%@] from type: [%@] transformer: [%@]", p.type, sourceClass, selectorName); //用字符串拼出转换函数的名称字符串,到JSONValueTransformer中去搜索@SEL执行出正确类型
//build a method selector for the property and json object classes
NSString* selectorName = [NSString stringWithFormat:@"%@From%@:",
(property.structName? property.structName : property.type), //target name
sourceClass]; //source name
SEL selector = NSSelectorFromString(selectorName); //check if there's a transformer with that name
if ([valueTransformer respondsToSelector:selector]) { //it's OK, believe me...
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
//transform the value
jsonValue = [valueTransformer performSelector:selector withObject:jsonValue];
#pragma clang diagnostic pop [self setValue:jsonValue forKey: property.name]; } else { // it's not a JSON data type, and there's no transformer for it
// if property type is not supported - that's a programmer mistaked -> exception
@throw [NSException exceptionWithName:@"Type not allowed"
reason:[NSString stringWithFormat:@"%@ type not supported for %@.%@", property.type, [self class], property.name]
userInfo:nil];
return nil;
} } else {
//哪儿都不是的直接存起来
// 3.4) handle "all other" cases (if any)
[self setValue:jsonValue forKey: property.name];
}
}
}
} //最后调用validate:看看结果是不是有效,没问题就返回了。
//run any custom model validation
NSError* validationError = nil;
BOOL doesModelDataValidate = [self validate:&validationError]; if (doesModelDataValidate == NO) {
if (err) *err = validationError;
return nil;
} //model is valid! yay!
return self;
}
程序亮点:
1、为了提高效率通过static的NSArray和NSDictionary进行解耦。
2、JSONValueTransformer实现了一个可复用的类型转换模板。
3、通过runtime function解析出property列表,通过property相关函数解析出名称,和Attributes的信息。
4、NSScanner的使用
5、NSSet的包含关系判断两个集合的交集
6、利用[NSObject setValue:forKey:]的KVO操作赋值,可以直接调用setter函数,并且可以赋nil到property中
7、适时给子类一个函数可以修改父类的一些行为
JSONModel源码阅读笔记的更多相关文章
- CI框架源码阅读笔记5 基准测试 BenchMark.php
上一篇博客(CI框架源码阅读笔记4 引导文件CodeIgniter.php)中,我们已经看到:CI中核心流程的核心功能都是由不同的组件来完成的.这些组件类似于一个一个单独的模块,不同的模块完成不同的功 ...
- CI框架源码阅读笔记4 引导文件CodeIgniter.php
到了这里,终于进入CI框架的核心了.既然是“引导”文件,那么就是对用户的请求.参数等做相应的导向,让用户请求和数据流按照正确的线路各就各位.例如,用户的请求url: http://you.host.c ...
- CI框架源码阅读笔记3 全局函数Common.php
从本篇开始,将深入CI框架的内部,一步步去探索这个框架的实现.结构和设计. Common.php文件定义了一系列的全局函数(一般来说,全局函数具有最高的加载优先权,因此大多数的框架中BootStrap ...
- CI框架源码阅读笔记2 一切的入口 index.php
上一节(CI框架源码阅读笔记1 - 环境准备.基本术语和框架流程)中,我们提到了CI框架的基本流程,这里再次贴出流程图,以备参考: 作为CI框架的入口文件,源码阅读,自然由此开始.在源码阅读的过程中, ...
- 源码阅读笔记 - 1 MSVC2015中的std::sort
大约寒假开始的时候我就已经把std::sort的源码阅读完毕并理解其中的做法了,到了寒假结尾,姑且把它写出来 这是我的第一篇源码阅读笔记,以后会发更多的,包括算法和库实现,源码会按照我自己的代码风格格 ...
- Three.js源码阅读笔记-5
Core::Ray 该类用来表示空间中的“射线”,主要用来进行碰撞检测. THREE.Ray = function ( origin, direction ) { this.origin = ( or ...
- PHP源码阅读笔记一(explode和implode函数分析)
PHP源码阅读笔记一一.explode和implode函数array explode ( string separator, string string [, int limit] )此函数返回由字符 ...
- AQS源码阅读笔记(一)
AQS源码阅读笔记 先看下这个类张非常重要的一个静态内部类Node.如下: static final class Node { //表示当前节点以共享模式等待锁 static final Node S ...
- libevent源码阅读笔记(一):libevent对epoll的封装
title: libevent源码阅读笔记(一):libevent对epoll的封装 最近开始阅读网络库libevent的源码,阅读源码之前,大致看了张亮写的几篇博文(libevent源码深度剖析 h ...
随机推荐
- HMM代码实践
本文主要转载于:http://www.52nlp.cn/hmm-learn-best-practices-eight-summary 这个文章是边看边实践加上自己的一些想法生成的初稿..... 状态转 ...
- 事后调试.ZC资料
1.查了一下,Delphi 程序 可以生成 map文件,可以用来 根据崩溃的内存报错 定位出错的代码位置 2.但是,Delphi程序 无法再崩溃的时候 生成dump文件 (这个不一定,研究了再说.记得 ...
- 【三小时学会Kubernetes!(零) 】系统结构及相关示例微服务介绍
写在前面 牢牢占据容器技术统治地位的 Kubernetes,其重要性想必不言而喻,我保证本文是最详尽的 Kubernetes 技术文档,从我在后台排版了这么漫长的时间就能看出来.废话不多说 — — 以 ...
- Android Fragment解析(上)
今天被人问到了什么是Fragment,真是一头雾水,虽然以前也用到过,但不知道它是叫这个名字,狂补一下. 以下内容来自互联网,原文链接:http://blog.csdn.net/lmj62356579 ...
- C++(三十二) — 常对象、常成员变量、常成员函数
常量:对于既需要共享.又需要防止改变的数据.在程序运行期间不可改变. const 修饰的是对象中的 this 指针.所以不能被修改. 1.常对象 数据成员值在对象的整个生存期内不能改变.在定义时必须初 ...
- hdu3544找规律
如果x>1&&y>1,可以简化到其中一个为1的情况,这是等价的,当其中一个为1(假设为x),另一个一定能执行y-1次, 这是一个贪心问题,把所有的执行次数加起来比较就能得到 ...
- poj-3046-dp
Ant Counting Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 6829 Accepted: 2514 Desc ...
- UVA-10917 Walk Through the Forest (dijkstra+DP)
题目大意:n个点,m条边的无向图.一个人从起点到终点按照下面的走法:从A走向B当A到终点的最小距离比B到终点的最小距离大时.问从起点到终点有多少路径方案. 题目分析:先用dijkstra预处理出终点到 ...
- Ansible 小手册系列 十二(Facts)
Facts 是用来采集目标系统信息的,具体是用setup模块来采集得. 使用setup模块来获取目标系统信息 ansible hostname -m setup 仅显示与ansible相关的内存信息 ...
- ansible入门七(实战)
Ansible实战:部署分布式日志系统 本节内容: 背景 分布式日志系统架构图 创建和使用roles JDK 7 role JDK 8 role Zookeeper role Kafka role ...