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源码阅读笔记的更多相关文章

  1. CI框架源码阅读笔记5 基准测试 BenchMark.php

    上一篇博客(CI框架源码阅读笔记4 引导文件CodeIgniter.php)中,我们已经看到:CI中核心流程的核心功能都是由不同的组件来完成的.这些组件类似于一个一个单独的模块,不同的模块完成不同的功 ...

  2. CI框架源码阅读笔记4 引导文件CodeIgniter.php

    到了这里,终于进入CI框架的核心了.既然是“引导”文件,那么就是对用户的请求.参数等做相应的导向,让用户请求和数据流按照正确的线路各就各位.例如,用户的请求url: http://you.host.c ...

  3. CI框架源码阅读笔记3 全局函数Common.php

    从本篇开始,将深入CI框架的内部,一步步去探索这个框架的实现.结构和设计. Common.php文件定义了一系列的全局函数(一般来说,全局函数具有最高的加载优先权,因此大多数的框架中BootStrap ...

  4. CI框架源码阅读笔记2 一切的入口 index.php

    上一节(CI框架源码阅读笔记1 - 环境准备.基本术语和框架流程)中,我们提到了CI框架的基本流程,这里再次贴出流程图,以备参考: 作为CI框架的入口文件,源码阅读,自然由此开始.在源码阅读的过程中, ...

  5. 源码阅读笔记 - 1 MSVC2015中的std::sort

    大约寒假开始的时候我就已经把std::sort的源码阅读完毕并理解其中的做法了,到了寒假结尾,姑且把它写出来 这是我的第一篇源码阅读笔记,以后会发更多的,包括算法和库实现,源码会按照我自己的代码风格格 ...

  6. Three.js源码阅读笔记-5

    Core::Ray 该类用来表示空间中的“射线”,主要用来进行碰撞检测. THREE.Ray = function ( origin, direction ) { this.origin = ( or ...

  7. PHP源码阅读笔记一(explode和implode函数分析)

    PHP源码阅读笔记一一.explode和implode函数array explode ( string separator, string string [, int limit] )此函数返回由字符 ...

  8. AQS源码阅读笔记(一)

    AQS源码阅读笔记 先看下这个类张非常重要的一个静态内部类Node.如下: static final class Node { //表示当前节点以共享模式等待锁 static final Node S ...

  9. libevent源码阅读笔记(一):libevent对epoll的封装

    title: libevent源码阅读笔记(一):libevent对epoll的封装 最近开始阅读网络库libevent的源码,阅读源码之前,大致看了张亮写的几篇博文(libevent源码深度剖析 h ...

随机推荐

  1. NNCRF之NNSegmentation, NNPostagging, NNNameEntity

    这里主要介绍NNSegmentation 介绍: NNSegmentation是一个基于LibN3L的利用神经网络来进行分词的工具. 他可以通过不同的模型(NN, RNN, GatedNN, LSTM ...

  2. Redis可以做哪些事儿?

    Redis可以作为数据库,提供高速缓存,消息队列等功能,这里介绍Redis可以做的其中两件事: 1.提供缓存功能,作为缓存服务器; 2.轻量级的消息队列(MQ)进行使用. /// <summar ...

  3. 关于Java中常用加密/解密方法的实现

    安全问题已经成为一个越来越重要的问题,在Java中如何对重要数据进行加密解密是本文的主要内容. 一.常用的加密/解密算法 1.Base64 严格来说Base64并不是一种加密/解密算法,而是一种编码方 ...

  4. SpringSecurity——基于Spring、SpringMVC和MyBatis自定义SpringSecurity权限认证规则

    本文转自:https://www.cnblogs.com/weilu2/p/springsecurity_custom_decision_metadata.html 本文在SpringMVC和MyBa ...

  5. C#多线程3种创建Thread、Delegate.BeginInvoke、线程池

    1   创建多线程,一般情况有以下几种:(1)通过Thread类   (2)通过Delegate.BeginInvoke方法   (3)线程池 using System; using System.C ...

  6. zsh 安装powerline 主题特效

    查看当前使用的shell脚本是哪一种   echo $0 1. 安装Powerline   使用pip指令,安装方法:   pip install powerline-status   如果没有,则先 ...

  7. Back Track5学习笔记

    1.BT5默认用户名:root.密码:toor(公司是yeslabccies) 2.进入图形化界面命令:startx 3.更改密码:sudo passwd root 扫描工具 第一部分网络配置: 4. ...

  8. mysql快问快答

    1.查看mysql版本 select version(); show variables like 'version'; 2.mysql 可以按timestamp排序吗? 可以 3.怎么查询商户下是否 ...

  9. tcpdump 使用实例

    详细的文档见tcpdump高级过滤技巧 基本语法 ========过滤主机--------- 抓取所有经过 eth1,目的或源地址是 192.168.1.1 的网络数据# tcpdump -i eth ...

  10. day36 爬虫+http请求+高性能

    爬虫 参考博客:http://www.cnblogs.com/wupeiqi/articles/5354900.html http://www.cnblogs.com/wupeiqi/articles ...