写在前面
每次写Json的数据解析的时候,就想到了小马哥的MJExtension。集成之后之后,基本上一句话搞定解析。但是每次都忘记,然后翻看之前的代码,至此记录一下。好记性,不如烂笔头啊!
先看一下数据格式
{
code = 0;
invitateCount = 2;
invitateForce = 20;
invitateList = (
{
headurl = "";
name = "";
time = 1565602627222;
userId = 1352;
},
{
headurl = "";
name = "";
time = 1565605057339;
userId = 1353;
}
);
remainCount = 48;
remainFore = 480;
}
MJExtension使用之后解析效果
//InvitateModel是接受的对象
InvitateModel *model = [InvitateModel mj_objectWithKeyValues:responseObj];
对,就是这么简单粗暴。
下面介绍一下使用技巧
首先需要声明 json数据的对象(Json最内层数组里面用一个对象InvitateUserMode
,最外层用一个对象InvitateModel
方法:从内往外)
对象InvitateUserModel
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface InvitateUserModel : NSObject
@property (nonatomic, strong)NSString *userId;
@property (nonatomic, strong)NSString *time;
@property (nonatomic, strong)NSString *name;
@property (nonatomic, strong)NSString *headurl;
@end
NS_ASSUME_NONNULL_END
对象InvitateModel
#import <Foundation/Foundation.h>
#import "InvitateUserModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface InvitateModel : NSObject
@property (nonatomic, strong)NSNumber *invitateCount;
@property (nonatomic, strong)NSNumber *invitateForce;
@property (nonatomic, strong)NSNumber *remainCount;
@property (nonatomic, strong)NSNumber *remainFore;
@property (nonatomic, strong)NSArray *invitateList;
@end
NS_ASSUME_NONNULL_END
#import "InvitateModel.h"
@implementation InvitateModel
+(NSDictionary *)mj_objectClassInArray {
//将声明invitateList接受的数据对象InvitateUserModel
return @{@"invitateList":@"InvitateUserModel"};
}
@end
下面直接开启请求模式
-(void)getUserInfoForceDeatil:(NSString *)userId {
NSDictionary *prams = @{
@"action":@"getForceDeatil",
@"requestParam": @{
@"userId":userId
}
};
WEAKSELF
[[ZSCNetworkManager shareInstance]requestForUrlWithMethodPOST:BaseURL withParams:prams withSuccess:^(id responseObj, BOOL isSuccess, NSString *message, NSInteger statusCode) {
if ([responseObj[@"code"] integerValue] == 0) {
InvitateModel *model = [InvitateModel mj_objectWithKeyValues:responseObj];
}
} withFail:^(NSError *error) {
}];
}
至此解析完成,是不是很简单。
再分享一个Json在转为model对象的过程中,直接对某些值的拦截操作技巧
场景1
实现代码
//监听键值
-(id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property {
if ([property.name isEqualToString:@"time"]) {
if (oldValue) {
//自定义的时间转换分类
NSString *timeStr = [NSString timestampSwitchTime:[oldValue integerValue]/1000 andFormatter:@"YYYY-MM-dd"];
return timeStr;
}else {
return @"日期有误";
}
}
return oldValue;
}
场景2
经常遇到后台返回字段名id
,而id
在前端确是关键字。此时就需要转为自己定义的成员名
实现代码
+ (NSDictionary *)mj_replacedKeyFromPropertyName{
return @{
@"userId" : @"id"//前边的是你想用的key,后边的是返回的key
};
}
欢迎评论区留言,一起学习!