iOS开源JSON解析库MJExtension

时间:2023-07-19 10:34:38

iOS中JSON与NSObject互转有两种方式:1、iOS自带类NSJSONSerialization 2、第三方开源库SBJSON、JSONKit、MJExtension。项目中一直用MJExtension来进行JSON与Model的互转,非常方便、强大,接下来介绍一下这个轻量、强大的开源库。

1、什么是MJExtension?

MJExtension是一套字典和模型之间互相转换的轻量级开源框架,github地址为:GitHub - CoderMJLee/MJExtension: A fast。功能如下:

JSON --> Model、Core Data Model

JSONString --> Model、Core Data Model

Model、Core Data Model --> JSON

JSON Array --> Model Array、Core Data Model Array

JSONString --> Model Array、Core Data Model Array

Model Array、Core Data Model Array --> JSON Array

Model Coding(归档和接档)

MJExtension特性在于JSON与Model的互转,避免了用NSJSONSerialization或者SBJSON、JSONKit等非Model解析库把JSON解析出成NSDictionary后到处用valueForKey或者objectForKey方法获取字段相应值所带来的麻烦,尤其是要在不同类之间传输数据的时候,传Model比传NSDictionary这种方式实在是方便优雅太多了

2、MJExtension架构

1)UML类图

iOS开源JSON解析库MJExtension

2)类介绍

NSObject+MJKeyValue(Model辅助类,提供字典字段到Model相应的属性转换)

NSObject+MJProperty(Model辅助类,封装Model属性操作)

MJProperty(Model属性封装类)

MJType(Model属性类型封装类)

NSObject(MJCoding)(Model归档和解档封装类)

3、MJExtension JSON转Model流程图

iOS开源JSON解析库MJExtension

4、MJExtension用法举例

关于用法详情请见:GitHub - CoderMJLee/MJExtension: A fast。我这里只介绍两种常用的用法,JSON转Model,JSON转Model数组

@interface PersonModel : NSObject

@property (nonatomic, copy) NSString* name;

@property (nonatomic, copy) NSString* sex;

@property (nonatomic, copy) NSString* age;

- (void)fetchPerson

{

__weak typeof(self)weakSelf = self;

fetchPersonRequest* request = [[fetchPersonRequest alloc] init];

[request startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {

NSDictionary* dic = [request.responseString JSONObject]; // request.responseString JSONString->NSDictionary

if (dic && ([[dic valueForKey:@"result"] integerValue] == 0))

{

weakSelf.personModel = [PersonModel objectWithKeyValues:[dic valueForKey:@"data"]]; //personModel为PersonModel对象,跟后台约定data字段为字典

//weakSelf.personModelArr = [PersonModel objectArrayWithKeyValuesArray:[dic valueForKey:@"data"]]; //personModelArr为PersonModel数组,跟后台约定data字段为字典数组

}

}

文/52xpz(简书作者)
原文链接:http://www.jianshu.com/p/5854081f052f
著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。