MCJSONKit
- JSON和模型之间快速、方便且非侵入性的转换。
- 快速、简单方便的字典转模型框架
目录
示例
要运行示例项目,首先克隆仓库,然后从 Example 目录运行 pod install
水平有限,不定期更新
-
这是一个经常被用于的第三方库,总是发现一些不够灵活或者有不足、不适用的地方,所以心血来潮自己写了一个轻量的JSON对象转换库。
-
目前为测试版,可能还有很多问题,会持续更新优化。
-
不改变目标对象的属性类型
-
null值不做处理,保持属性的默认值
-
过滤类型不匹配的情况,例如
类型为NSArray,但是JSON数据为字符串的情况
-
代码覆盖率100%
-
待完善
JavaScript 对象表示法,或 [JSON][], 是一种轻量级、基于文本的用于结构化数据的序列化格式,被许多基于Web的服务和 API 所使用。它由 RFC 4627 定义。
JSON提供了以下原始类型
null
- 布尔值
true
和false
- 数字
- 字符串
- 数组
- 对象
这些原始类型映射到以下 Objective-C Foundation 类
JSON | Objective-C |
---|---|
null |
[nil ] |
true 和 false |
[NSNumber ] 或 [BOOL ] |
数字 | [NSNumber ] 或 [NSDate ] |
字符串 | [NSString ] |
数组 | [NSArray ] |
对象 | [NSDictionary ] |
NSJSONReadingOptions
NSJSONReadingMutableContainers // 返回可变容器,NSMutableDictionary或NSMutableArray
NSJSONReadingMutableLeaves // 不仅返回的最外层是可变的, 内部的子数值或字典也是可变对象
NSJSONReadingAllowFragments // 返回允许JSON字符串最外层既不是NSArray也不是NSDictionary,但必须是有效的JSON Fragment.可以是例如 "10"
NSJSONWritingOptions
NSJSONWritingPrettyPrinted = (1UL << 0) //是将生成的json数据格式化输出,这样可读性高,不设置则输出的json字符串就是一整行。
NSJSONWritingSortedKeys //输出的json字符串就是一整行
如何使用
MCJSONKit 可通过 CocoaPods 获取。要安装它,只需将以下行添加到您的 Podfile 中
pod "MCJSONKit"
#import <MCJSONKit/MCJSONKit.h>
或者将 MJJSONKit 文件夹导入您的项目
#import "MCJSONKit.h"
示例
创建基础模型YourBaseModel并封装【推荐】
使用时再封装一层,方便以后迁移
示例:iOSExample->Weibo->Models->WeiboModel.h(包含MJExtension的实现方式作为对比)
#import <MCJSONKit/MCJSONKit.h>
//示例基础模型
@interface YourBaseJSONModel : NSObject
/**
通过字典创建模型
@param data 许可类型<NSData,NSDictionary,NSString>
@return 新创建模型对象
*/
+ (instancetype)jsonObjectFromData:(id)data;
+ (NSArray *)arrayOfModelsFromKeyValues:(id)keyValues;
/**
允许的属性集合,配置后则ignoreSet失效
*/
- (NSSet *)allowedPropertyNames;
/**
忽略的属性集合
*/
- (NSSet *)ignoreSet;
/**
key关联字段
@return key:对象属性 value:keyPath
*/
- (NSDictionary *)keyMappingDictionary;
/**
类型关联字典
@return key:对象属性 value:类型class
*/
- (NSDictionary *)typeMappingDictionary;
- (NSDictionary *)toDictionary;
- (NSString *)toJSONString;
@end
#import "YourBaseModel.h"
#import "NSObject+MCJSONKit.h"
#import "MJExtension.h"
@implementation YourBaseModel
+ (void)load {
//格式化输出JSON字符串,默认为NO
[self setPrettyPrinted:YES];
}
- (void)setCreated_at:(NSString *)created_at {
NSDateFormatter *dateFmt = [NSDateFormatter new];
dateFmt.dateFormat = @"EEE MMM d HH:mm:ss Z yyyy";
dateFmt.locale = [NSLocale localeWithLocaleIdentifier:@"en-US"];
NSDate *date = [dateFmt dateFromString:created_at];
_created_at = @(date.timeIntervalSince1970).stringValue;
}
#pragma mark - 二次封装JSONKit
+ (instancetype)jsonObjectFromData:(id)data {
return [self mc_objectFromKeyValues:data];
}
+ (NSArray *)arrayOfModelsFromKeyValues:(id)keyValues {
return [self mc_arrayOfModelsFromKeyValues:keyValues];
}
- (NSSet *)allowedPropertyNames {
return nil;
}
- (NSDictionary *)keyMappingDictionary {
return nil;
}
- (NSDictionary *)typeMappingDictionary {
return nil;
}
- (NSSet *)ignoreSet {
return nil;
}
- (NSDictionary *)toDictionary {
return [self mc_toDictionary];
}
- (NSString *)toJSONString {
return [self mc_JSONString];
}
#pragma mark JSONCoreConfig
- (NSSet *)mc_allowedPropertiesSet {
return [self allowedPropertyNames];
}
- (NSDictionary *)mc_keyMappingDictionary {
return [self keyMappingDictionary];
}
- (NSDictionary *)mc_typeMappingDictionary {
return [self typeMappingDictionary];
}
- (NSSet *)mc_ignorePropertiesSet {
return [self ignoreSet];
}
@end
JSONString -> Model【简单模型】
{ "id": 10, "country": "Germany", "dialCode": 49, "isInEurope": true }
@interface CountryModel : YourBaseModel
@property (nonatomic) NSInteger id;
@property (nonatomic) NSString *country;
@property (nonatomic) NSString *dialCode;
@property (nonatomic) BOOL isInEurope;
@end
CountryModel *country = [CountryModel jsonObjectFromData:jsonString];
JSON字符串 -> 模型【模型嵌套】
{
"orderId": 104,
"totalPrice": 103.45,
"products": [
{
"id": 123,
"name": "Product #1",
"price": 12.95
},
{
"id": 137,
"name": "Product #2",
"price": 82.95
}
],
"status":{
"code":1,
"msg":"订单已付款"
}
}
@interface ProductModel : YourBaseModel
@property (nonatomic) NSInteger productId;
@property (nonatomic) NSString *name;
@property (nonatomic) float price;
@end
@interface OrderModel : YourBaseModel
@property (nonatomic) NSInteger orderId;
@property (nonatomic) float totalPrice;
@property (nonatomic, assign) int status;
@property (nonatomic) NSArray<ProductModel *> *products;
@end
模型名称 - JSON键映射【属性和字典的key不同、多级映射】
@implementation ProductModel
- (NSDictionary *)keyMappingDictionary {
return @{MCProperty(productID):@"id"};
}
@end
@implementation OrderModel
- (NSDictionary *)keyMappingDictionary {
return @{MCProperty(status):@"status.code"};
}
@end
模型包含数组模型【包含模型数组】
//模型中有个数组属性,数组元素映射为其他模型
- (NSDictionary *)typeMappingDictionary {
return @{MCProperty(products):[ProductModel class]};
}
解析速度对比
100次循环解析 | 平均耗时 |
---|---|
MCJSONKit |
0.415秒 |
MJExtension |
0.626秒 |
待办事项
- 解析速度对比分析
- 复杂JSON解析测试
- 全面覆盖测试,找出BUG
许可证
MCJSONKit 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件。