详解Obejective-C中将JSON数据转为模型的方法

前端技术 2023/09/04 IOS

在我们的日常开发中需要对加载的一些本地数据例如plist、json等文件中的数据进行模型转化,而苹果也为我们提供了一种非常方便的键值转换方式KVC。然而KVC在某些情况下并不能保存数据的转换成功,比如必须保证模型的属性个数大于等于字典个数,也要必须属性名称与字典的key相同等。所以这次我们假设下属性名称与字典中的key不一致的时候转换方法。
首先我们还是先要尝试下使用KVC的方式来解决这个问题
模型如下:

jastor这个库,也会方便很多现在就基本的用法做个介绍。

假如我们有如下这么一个类

复制代码 代码如下:

#import <Foundation/Foundation.h>
#import \"Jastor.h\"

@interface DeviceEntity : Jastor

@property (nonatomic,strong) NSNumber *isonline;
@property (nonatomic,strong) NSNumber *isopen;
@property (nonatomic,copy) NSString *brand;

@end

#import \"DeviceEntity.h\"

@implementation DeviceEntity

@synthesize isopen,isonline,brand;

@end

#import <Foundation/Foundation.h>
#import \"Jastor.h\"
#import \"DeviceEntity.h\"

@interface UserDevicesEntity : Jastor

@property (nonatomic,strong) NSNumber *closecount;
@property (nonatomic,strong) NSNumber *opencount;
@property (nonatomic,copy) NSString *success;
@property (nonatomic,strong) NSArray *items;

@end

#import \"UserDevicesEntity.h\"
#import \"DeviceEntity.h\"

@implementation UserDevicesEntity

@synthesize closecount,opencount,success,items;

+ (Class) items_class {
    return [DeviceEntity class];
}

@end

本文地址:https://www.stayed.cn/item/10706

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。