JSONModel源码阅读笔记

JSONModel是一个解析服务器返回的Json数据的库。

通常服务器传回的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、适时给子类一个函数可以修改父类的一些行为

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


文章浏览阅读2.4k次。最近要优化cesium里的热力图效果,浏览了网络上的各种方法,发现大多是贴在影像上的。这么做好是好,但是会被自生添加的模型或者其他数据给遮盖。其次是网上的方法大多数是截取成一个矩形。不能自定义的截取自己所需要的。经过尝试,决定修改下cesium heatmap,让他达到我们需要的要求。首先先下载 cesium heatmap包。其中我们可以看到也是通过叠加entity达到添加canvas的方法绘制到地图上。我们先把这一段代码注释} else {} };
文章浏览阅读1.2w次,点赞3次,收藏19次。在 Python中读取 json文件也可以使用 sort ()函数,在这里我介绍一个简单的示例程序: (4)如果我们想将字符串转换为列表形式,只需要添加一个变量来存储需要转换的字符串即可。在上面的代码中,我们创建了一个名为` read`的对象,然后在文件的开头使用`./`关键字来命名该对象,并在文件中定义了一个名为` json`的变量,并在其中定义了一个名为` json`的字段。比如,我们可以使用 read方法读取 json文件中的内容,然后使用 send方法将其发送到 json文件中。_python怎么读取json文件
文章浏览阅读1.4k次。首字母缩略词 API 代表应用程序编程接口,它是一种设备,例如用于使用编程代码发送和检索数据的服务器。最常见的是,该技术用于从源检索数据并将其显示给软件应用程序及其用户。当您访问网页时,API 的工作方式与浏览器相同,信息请求会发送到服务器,如何在 Windows PC 中手动创建系统还原点服务器会做出响应。唯一的区别是服务器响应的数据类型,对于 API,数据是 JSON 类型。JSON 代表 JavaScript Object Notation,它是大多数软件语言中 API 的标准数据表示法。_api是什么 python
文章浏览阅读802次,点赞10次,收藏10次。解决一个JSON反序列化问题-空字符串变为空集合_cannot coerce empty string ("") to element of `java.util.arraylist
文章浏览阅读882次。Unity Json和Xml的序列化和反序列化_unity json反序列化存储换行
文章浏览阅读796次。reader.readAsText(data.file)中data.file的数据格式为。使用FileReader对象读取文件内容,最后将文件内容进行处理使用。_a-upload 同时支持文件和文件夹
文章浏览阅读775次,点赞19次,收藏10次。fastjson是由国内的阿里推出的一种json处理器,由java语言编写,无依赖,不需要引用额外的jar包,能直接运行在jdk环境中,它的解析速度是非常之快的,目前超过了所有json库。提示:以下是引用fastjson的方法,数据未涉及到私密信息。_解析器用fastjson还是jackson
文章浏览阅读940次。【Qt之JSON文件】QJsonDocument、QJsonObject、QJsonArray等类介绍及使用_使用什么方法检查qjsondocument是否为空
文章浏览阅读957次,点赞34次,收藏22次。主要内容原生 ajax重点重点JSON熟悉章节目标掌握原生 ajax掌握jQuery ajax掌握JSON第一节 ajax1. 什么是ajaxAJAX 全称为,表示异步的Java脚本和Xml文件,是一种异步刷新技术。2. 为什么要使用ajaxServlet进行网页的变更往往是通过请求转发或者是重定向来完成,这样的操作更新的是整个网页,如果我们只需要更新网页的局部内容,就需要使用到AJAX来处理了。因为只是更新局部内容,因此,Servlet。
文章浏览阅读1.4k次,点赞45次,收藏13次。主要介绍了JsonFormat与@DateTimeFormat注解实例解析,文中通过示例代码介绍的非常详细,对大家的学习 或者工作具有一定的参考学习价值,需要的朋友可以参考下 这篇文章主要介绍了从数据库获取时间传到前端进行展示的时候,我们有时候可能无法得到一个满意的时间格式的时间日期,在数据库中显 示的是正确的时间格式,获取出来却变成了时间戳,@JsonFormat注解很好的解决了这个问题,我们通过使用 @JsonFormat可以很好的解决:后台到前台时间格式保持一致的问题,
文章浏览阅读1k次。JsonDeserialize:json反序列化注解,作用于setter()方法,将json数据反序列化为java对象。可以理解为用在处理接收的数据上。_jsondeserialize
文章浏览阅读2.7k次。labelme标注的json文件是在数据标注时产生,不能直接应用于模型训练。各大目标检测训练平台或项目框架均有自己的数据格式要求,通常为voc、coco或yolo格式。由于yolov8项目比较火热,故此本博文详细介绍将json格式标注转化为yolo格式的过程及其代码。_labelme json 转 yolo
文章浏览阅读790次,点赞26次,收藏6次。GROUP_CONCAT_UNORDERED(): 与GROUP_CONCAT类似,但不保证结果的顺序。COUNT_DISTINCT_AND_ORDERED(): 计算指定列的不同值的数量,并保持结果的顺序。COUNT_ALL_DISTINCT(): 计算指定列的所有不同值的数量(包括NULL)。AVG_RANGE(): 计算指定列的最大值和最小值之间的差异的平均值。JSON_OBJECT(): 将结果集中的行转换为JSON对象。COUNT_DISTINCT(): 计算指定列的不同值的数量。_mysql json 聚合
文章浏览阅读1.2k次。ajax同步与异步,json-serve的安装与使用,node.js的下载_json-serve 与node版本
文章浏览阅读1.7k次。`.net core`提供了Json处理模块,在命名空间`System.Text.Json`中,下面通过顶级语句,对C#的Json功能进行讲解。_c# json
文章浏览阅读2.8k次。主要介绍了python对于json文件的读写操作内容_python读取json文件
文章浏览阅读770次。然而,有时候在处理包含中文字符的Json数据时会出现乱码的情况。本文将介绍一种解决Json中文乱码问题的常见方法,并提供相应的源代码和描述。而某些情况下,中文字符可能会被错误地编码或解码,导致乱码的出现。通过适当地控制编码和解码过程,我们可以有效地处理包含中文字符的Json数据,避免乱码的发生。通过控制编码和解码过程,我们可以确保Json数据中的中文字符能够正确地传输和解析。为了解决这个问题,我们可以使用C#的System.Text.Encoding类提供的方法进行编码和解码的控制。_c# json 中文编码
文章浏览阅读997次。【代码】【工具】XML和JSON互相转换。_xml 转json
文章浏览阅读1.1k次。json path 提取数据_jsonpath数组取值
文章浏览阅读3w次,点赞35次,收藏36次。本文主要介绍了pandas read_json时ValueError: Expected object or value的解决方案,希望能对学习python的同学们有所帮助。文章目录1. 问题描述2. 解决方案_valueerror: expected object or value