IOS开发-MJExtension常用的数据类型和模型转化

1.字典转模型

核心方法: mj_objectWithKeyValues:

UserModel模型类,UserModel.h代码为:

//
//  UserModel.h
//  NSURLSessionDemo
//
//  Created by liuwenbo on 2021/5/27.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

typedef enum {
    SexMale,
    SexFemale
} Sex;

@interface UserModel : NSObject
@property (copy, nonatomic) NSString *name;/* 姓名 */
@property (copy, nonatomic) NSString *icon;/* 头像 */
@property (assign, nonatomic) unsigned int age;/* 年龄 */
@property (copy, nonatomic) NSString *height;/* 身高 */
@property (strong, nonatomic) NSNumber *money;/* 资产 */
@property (assign, nonatomic) Sex sex;/* 性别 */
@property (assign, nonatomic, getter=isGay) BOOL gay;/* 是否是同性恋 */
@end

NS_ASSUME_NONNULL_END

UserModel.m 为默认。

字典转模型的代码(ViewController.m中)为:

#pragma mark 字典转模型
- (void)dictToModel {
    NSDictionary *dictUser = @{
       @"name" : @"Jack",
       @"icon" : @"lufy.png",
       @"age" : @20,
       @"height" : @"1.55",
       @"money" : @100.9,
       @"sex" : @(SexFemale),/* 枚举需要使用NSNumber包装 */
       @"gay" : @NO
    };
    UserModel *userModel = [UserModel mj_objectWithKeyValues:dictUser];
    NSLog(@"MJ---%@----%@---%u---%@---%@---%u----%d",userModel.name, userModel.icon, userModel.age, userModel.height, userModel.money, userModel.sex, userModel.gay);
}

2.Json字符串转模型

同样还是使用UserModel模型类,核心方法为:mj_objectWithKeyValues

#pragma mark Json 字符串转模型
- (void)JsonStringToModel {
    // 定义一个JSON字符串
    NSString *jsonStr = @"{\"name\":\"Jack\", \"icon\":\"lufy.png\",\"age\":20}";
    UserModel *userModel = [UserModel mj_objectWithKeyValues:jsonStr];
    NSLog(@"MJ---%@----%@---%u---%@---%@---%u----%d",userModel.name, userModel.icon, userModel.age, userModel.height, userModel.money, userModel.sex, userModel.gay);
}

3.复杂的字典(字典套字典)转模型(模型里面包含了模型)

新建模型类:StatusModel,StatusModel.h代码为:

//
//  StatusModel.h
//  NSURLSessionDemo
//
//  Created by liuwenbo on 2021/5/27.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN
@class UserModel;
@class StatusModel;
@interface StatusModel : NSObject
@property (copy, nonatomic) NSString *text;
@property (strong, nonatomic) UserModel *user;/* 其他模型类型 */
@property (strong, nonatomic) StatusModel *status;/* 自我模型类型 */
@end

NS_ASSUME_NONNULL_END

StatusModel.m为默认。
复杂字典转模型的代码(ViewController.m中)为:

#pragma mark 复杂的字典(模型里面包含了模型)转模型
- (void)comlexDictToModel {
    //复杂的字典[模型中有个数组属性,数组里面又要装着其他模型的字典]
    NSDictionary *dict = @{
        @"text" : @"Agree!Nice weather!",
        @"user" : @{
            @"name" : @"Jack",
            @"icon" : @"lufy.png"
        },
        @"status" : @{
            @"text" : @"Nice weather!",
            @"user" : @{
                @"name" : @"Rose",
                @"icon" : @"nami.png"
            }
        }
    };
    StatusModel *statusModel = [StatusModel mj_objectWithKeyValues:dict];
    NSString *text = statusModel.text;
    NSString *userName = statusModel.user.name;
    NSString *iconName = statusModel.user.icon;
    NSLog(@"text=%@, name=%@, icon=%@", text, userName, iconName);
    
    NSString *text1 = statusModel.status.text;
    NSString *userName1 = statusModel.status.user.name;
    NSString *iconName1 = statusModel.status.user.name;
    NSLog(@"text=%@, name=%@, icon=%@", text1, userName1, iconName1);
}

4.模型中有个数组属性,数组里面又要装着其它模型

核心代码: mj_objectWithKeyValues:mj_objectClassInArray

新建模型类:StatusResultModel,StatusResultModel.h代码如下:

//
//  StatusResultModel.h
//  NSURLSessionDemo
//
//  Created by liuwenbo on 2021/5/27.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface StatusResultModel : NSObject
/** 存放着一堆的数据(里面都是StatusModel) */
@property (strong, nonatomic) NSMutableArray *statuses;
/** 存放着一堆的数据(里面都是UserModel) */
@property (strong, nonatomic) NSArray *users;
@property (strong, nonatomic) NSNumber *totalNumber;
@end

NS_ASSUME_NONNULL_END

StatusResultModel.m中代码如下:

//
//  StatusResultModel.m
//  NSURLSessionDemo
//
//  Created by liuwenbo on 2021/5/27.
//

#import "StatusResultModel.h"

@implementation StatusResultModel

/* 数组中存储模型数据,需要说明数组中存储的模型数据类型 */
+ (NSDictionary *)mj_objectClassInArray {
    return @{
        @"statuses" : @"StatusModel", // 前边是属性数组的名字,后面是模型类名
        @"users" : @"UserModel"
    };
}
@end

在viewController.m 中实现解析数据:

#pragma mark 模型中有个数组属性,数组里面又要装着其它模型
- (void)complexDictAndArrayToModel {
    NSDictionary *dict = @{
        @"statuses" : @[
            @{
                @"text" : @"Nice weather!",
                @"user" : @{
                    @"name" : @"Rose",
                    @"icon" : @"nami.png"
                }
            },
            @{
                @"text" : @"Go camping tomorrow!",
                @"user" : @{
                    @"name" : @"Jack",
                    @"icon" : @"lufy.png"
                }
            }
        ],
        @"users" : @[
            @{
                @"name" : @"zhangsan",
                @"icon" : @"ad01.png"
            },
            @{
                @"name" : @"lisi",
                @"icon" : @"ad02.png"
            }
        ],
        @"totalNumber" : @"2014"
    };
    StatusResultModel *statusResultModel = [StatusResultModel mj_objectWithKeyValues:dict];
    [statusResultModel.statuses enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        StatusModel *model = (StatusModel *)obj;
        NSLog(@"text:%@, name:%@, icon:%@", model.text, model.user.name, model.user.icon);
    }];
    [statusResultModel.users enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UserModel *model = (UserModel *)obj;
        NSLog(@"name:%@, icon:%@", model.name, model.icon);
    }];
}

5.模型数据中的属性名和字典中的key不相同(或者需要多级映射)

核心代码 mj_objectWithKeyValues:mj_replacedKeyFromPropertyName
新建模型类StudentModel,其中StudentModel.h代码如下:

//
//  StudentModel.h
//  NSURLSessionDemo
//
//  Created by liuwenbo on 2021/5/27.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN
@class BagModel;
@interface StudentModel : NSObject
@property (copy, nonatomic) NSString *ID;
@property (copy, nonatomic) NSString *desc;
@property (copy, nonatomic) NSString *nowName;
@property (copy, nonatomic) NSString *oldName;
@property (copy, nonatomic) NSString *nameChangedTime;
@property (nonatomic, strong) BagModel *bag;
@end

NS_ASSUME_NONNULL_END

StudentModel.m代码如下:

//
//  StudentModel.m
//  NSURLSessionDemo
//
//  Created by liuwenbo on 2021/5/27.
//

#import "StudentModel.h"

@implementation StudentModel
// 实现这个方法的目的是 告诉MJExtension框架中的属性名对应着字典的哪个key
+ (NSDictionary *)mj_replacedKeyFromPropertyName {
    return @{
        @"ID":@"id",
        @"desc" : @"desciption",
        @"oldName" : @"name.oldName",
        @"nowName" : @"name.newName",
        @"nameChangedTime" : @"name.info[0].nameChangedTime",
        @"bag" : @"other.bag"
    };
}
@end

这里BagModel模型类定义如下:

//
//  BagModel.h
//  NSURLSessionDemo
//
//  Created by liuwenbo on 2021/5/27.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface BagModel : NSObject

@property (nonatomic, strong)NSString *name;
@property (nonatomic, assign)double price;

@end

NS_ASSUME_NONNULL_END

在ViewController.m中解析数据

#pragma mark 模型数据中的属性名和字典中的key不相同(或者需要多级映射)
- (void)attributeNoeEqualKeyToModel {
    NSDictionary *dict = @{
        @"id" : @"20",
        @"desciption" : @"kids",
        @"name" : @{
            @"newName" : @"lufy",
            @"oldName" : @"kitty",
            @"info" : @[
                @"test-data",
                @{
                    @"nameChangedTime" : @"2013-08"
                }
            ]
        },
        @"other" : @{
            @"bag" : @{
                @"name" : @"a red bag",
                @"price" : @100.7
            }
        }
    };
    StudentModel *studentModel = [StudentModel mj_objectWithKeyValues:dict];
    NSLog(@"ID=%@, desc=%@, oldName=%@, nowName=%@, nameChangedTime=%@",
          studentModel.ID, studentModel.desc, studentModel.oldName, studentModel.nowName, studentModel.nameChangedTime);
    // 头文件中必须函数bag模型的头文件才可能被打印
    NSLog(@"bagName=%@, bagPrice=%f", studentModel.bag.name, studentModel.bag.price);
}

6. 将一个字典数组转成模型数组

核心代码 mj_objectArrayWithKeyValuesArray

使用上面的模型类,不需要重新创建,VIewController.m中代码如下:

#pragma mark 将一个字典数组转化成模型
- (void)dictArrayToModel {
    NSArray *dictArray = @[
        @{
            @"name" : @"Jack",
            @"icon" : @"Jack.jpg"
        },
        @{
            @"name" : @"lee",
            @"icon" : @"lee.jpg"
        }
    ];
    NSArray *userModelArray = [UserModel mj_objectArrayWithKeyValuesArray:dictArray];
    [userModelArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UserModel *model = (UserModel *)obj;
        NSLog(@"name:%@, icon:%@", model.name, model.icon);
    }];
}

7.将一个模型转成字典

核心代码 mj_keyValues
使用上面的模型类,不需要重新创建,VIewController.m中代码如下:

#pragma mark 将一个模型转成字典
- (void)modelToDict {
    UserModel *userModel = [[UserModel alloc] init];
    userModel.name = @"Jack";
    userModel.icon = @"Jack.jpg";
    // 模型转字典
    NSDictionary *dict = userModel.mj_keyValues;
    NSLog(@"%@", dict);
}

8. 将一个模型数组转成字典数组

核心代码 mj_keyValuesArrayWithObjectArray

#pragma mark 将一个模型数组转成字典数组
- (void)modelArrayToDictArray {
    UserModel *userModel1 = [[UserModel alloc] init];
    userModel1.name = @"Jack";
    userModel1.icon = @"Jack.jpg";
    
    UserModel *userModel2 = [[UserModel alloc] init];
    userModel2.name = @"lee";
    userModel2.icon = @"lee.jpg";
    // 模型数组
    NSArray *modelArray =@[userModel1, userModel2];
    // 模型数组转成字典数组
    NSArray *dictArray = [UserModel mj_keyValuesArrayWithObjectArray:modelArray];
    NSLog(@"%@", dictArray);
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值