zoukankan      html  css  js  c++  java
  • IOS JSON转换模型库:YYMODEL

    其实在研究这个库之前,市面上已经有很多类似的模型序列化成JSON及反序列化库(如Mantle、MJExtension)了,推荐他只是因为他高端的性能和容错(错误对象类型赋值到属性时YYMODEL会尝试自动转换,避免Crash)以及低侵入(不需要你的MODEL类去继承某个基类、因为他是Category 方式来实现的)。作者号称对比性能如下:

    屏幕快照 2016-03-18 下午1.25.35

    接下来直接写一个小例子看如何使用:

    1.首先准备JSON及对象如下:

     1 {
     2 "userName": "向阳",
     3 "userPass": "xiang",
     4 "age": 10,
     5 "ident": [
     6 {
     7 "price": 100.56,
     8 "priceDate": "1987-06-13 00:00:00"
     9 },
    10 {
    11 "price": 100,
    12 "priceDate": "1987-06-13"
    13 }
    14 ]
    15 }

    模型:Ident

    1 @interface Ident : NSObject
    2 @property(nonatomic,strong) NSNumber* price;
    3 @property(nonatomic,strong) NSDate* priceDate;
    4 @end
    5 #import "Ident.h"
    6 @implementation Ident
    7 @end

    模型:User (对象有包含关系时,在包含类的中需要申明一个modelContainerPropertyGenericClass方法,并标明对应属性以及转换的对象类。如这里的User包含了Ident)

    1 #import <Foundation/Foundation.h>
    2 #import "Ident.h"
    3 @interface User : NSObject
    4 @property(nonatomic,strong)NSString* userName;
    5 @property(nonatomic,strong)NSString* userPass;
    6 @property(nonatomic,strong)NSNumber* age;
    7 @property(nonatomic,strong)NSArray<Ident*>* ident;
    8 @end
    1 #import "User.h"
    2 #import "Ident.h"
    3 @implementation User
    4 // 返回容器类中的所需要存放的数据类型 (以 Class 或 Class Name 的形式)。
    5 + (NSDictionary *)modelContainerPropertyGenericClass {
    6 return @{@"ident" : [Ident class]};
    7 }
    8 @end

    2.使用方法(yy_modelWithJSON、yy_modelToJSONObject)

    yy_modelWithJSON:将 JSON (NSData,NSString,NSDictionary) 转换为 Model
    yy_modelToJSONObject:将Model转换成NSDictionary以及NSArray

    1 User *user = [User yy_modelWithJSON:jsonString];
    2 NSLog(@"%@",user.ident[0].priceDate);
    3 // 将 Model 转换为 JSON 对象:
    4 NSDictionary *json = [user yy_modelToJSONObject];
  • 相关阅读:
    singleTon 模式
    最近的工作经验
    sql server里的快捷键
    Bridge 模式
    [转]在.NET客户端程序中使用多线程
    wse
    关于高频查询界面
    判断字段值已经存在
    获取当前供应商的联系人信息
    获取系统常量
  • 原文地址:https://www.cnblogs.com/fengmin/p/5377263.html
Copyright © 2011-2022 走看看