要运行示例项目,请在拉取代码后,先在Pods
目录执行pod install
命令。
To run the example project, clone the repo, and run pod install
from the Pods directory first.
iOS 11.0, Xcode 14.0
推荐使用 CocoaPods 安装 XZJSON 组件,在Podfile
文件中添加下面这行代码即可。
XZJSON is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod 'XZJSON'
XZJSON 基于 YYModel 打造,主要解决 YYModel 不再维护的问题。
XZJSON 采用 “工具类” + “协议” 的方式实现,这与 YYModel 设计思路不同。
1、JSON 数据 Model 化
Model *model = [XZJSON decode:data options:(NSJSONReadingAllowFragments) class:[Model class]];
2、Model 对象 JSON 序列化
NSData *json = [XZJSON encode:model options:NSJSONWritingPrettyPrinted error:nil];
3、其它功能
- Model 属性与 JSON 键映射
+ (NSDictionary<NSString *,id> *)mappingJSONCodingKeys {
return @{
@"identifier": @"id"
};
}
- 不透明对象类型映射
+ (NSDictionary<NSString *,id> *)mappingJSONCodingClasses {
return @{
@"students": [Student class]
};
}
- 自定义模型化过程、数据校验
- (instancetype)initWithJSONDictionary:(NSDictionary *)JSON {
[XZJSON object:self decodeWithDictionary:JSON];
[self.students enumerateObjectsUsingBlock:^(Student * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
obj.teacher = self;
}];
return self;
}
- 白名单、黑名单
+ (NSArray<NSString *> *)allowedJSONCodingKeys {
return nil; // allow all
}
+ (NSArray<NSString *> *)blockedJSONCodingKeys {
return @[@"teacher"];
}
- 模型转发
+ (nullable Class)forwardingClassForJSONDictionary:(NSDictionary *)JSON {
// 在此方法中,可通过对 JSON 数据进行判断,返回适合的模型进行解析数据。
return SomeModelClass;
}
- 前置数据校验。
+ (nullable NSDictionary *)canDecodeFromJSONDictionary:(NSDictionary *)JSON {
// 在此方法中,可校验或修改数据,返回 nil 表示数据不合法,停止模型化
}
- 自定义 JSON 序列化。
- (nullable NSDictionary *)encodeIntoJSONDictionary:(NSMutableDictionary *)dictionary {
[XZJSON object:self encodeIntoDictionary:dictionary];
dictionary[@"date"] = @(NSDate.date.timeIntervalSince1970); // 自定义:向序列化数据中,加入一个时间戳
return dictionary;
}
Xezun, [email protected]
XZJSON is available under the MIT license. See the LICENSE file for more info.