Giter Site home page Giter Site logo

codermjlee / mjextension Goto Github PK

View Code? Open in Web Editor NEW
8.5K 327.0 2.2K 2.65 MB

A fast, convenient and nonintrusive conversion framework between JSON and model. Your model class doesn't need to extend any base class. You don't need to modify any model file.

License: MIT License

Objective-C 90.04% Ruby 0.63% Swift 9.33%
objective-c model json dictionary array

mjextension's Introduction

MJExtension

SPM supported Carthage compatible podversion Platform

  • A fast, convenient and nonintrusive conversion framework between JSON and model.
  • 转换速度快、使用简单方便的字典转模型框架

📜✍🏻Release Notes: more details

Contents


Getting Started【开始使用】

Features【能做什么】

  • MJExtension是一套字典和模型之间互相转换的超轻量级框架
  • JSON --> ModelCore Data Model
  • JSONString --> ModelCore Data Model
  • ModelCore Data Model --> JSON
  • JSON Array --> Model ArrayCore Data Model Array
  • JSONString --> Model ArrayCore Data Model Array
  • Model ArrayCore Data Model Array --> JSON Array
  • Coding all properties of a model with only one line of code.
    • 只需要一行代码,就能实现模型的所有属性进行Coding / SecureCoding(归档和解档)

Installation【安装】

CocoaPods【使用CocoaPods】

pod 'MJExtension'

Carthage

github "CoderMJLee/MJExtension"

Swift Package Manager

Released from 3.4.0

Manually【手动导入】

  • Drag all source files under folder MJExtension to your project.【将MJExtension文件夹中的所有源代码拽入项目中】
  • Import the main header file:#import "MJExtension.h"【导入主头文件:#import "MJExtension.h"

Examples【示例】

Add MJKeyValue protocol to your model if needed【如果有需要, 请在模型中加入 MJKeyValue 协议】

Usage in Swift [关于在Swift中使用MJExtension] ‼️

Example:

@objc(MJTester)
@objcMembers
class MJTester: NSObject {
    // make sure to use `dynamic` attribute for basic type & must use as Non-Optional & must set initial value
    dynamic var isSpecialAgent: Bool = false
    dynamic var age: Int = 0
    
    var name: String?
    var identifier: String?
}
  1. @objc or @objcMembers attributes should be added to class or property for declaration of Objc accessibility [在 Swift4 之后, 请在属性前加 @objc 修饰或在类前增加 @objcMembers. 以保证 Swift 的属性能够暴露给 Objc 使用. ]
  2. If you let Bool & Int as property type, make sure that using dynamic to attribute it. It must be Non-Optional type and assign a default value.[如果要使用 BoolInt 等 Swfit 专用基本类型, 请使用 dynamic 关键字修饰, 类型为 Non-Optional, 並且给定初始值.]

纯Swift版的JSON与Model转换框架已经开源上架

  • KakaJSON
  • 中文教程
  • 如果你的项目是用Swift写的Model,墙裂推荐使用KakaJSON
    • 已经对各种常用的数据场景进行了大量的单元测试
    • 简单易用、功能丰富、转换快速

The most simple JSON -> Model【最简单的字典转模型】

typedef enum {
    SexMale,
    SexFemale
} Sex;

@interface User : 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

/***********************************************/

NSDictionary *dict = @{
    @"name" : @"Jack",
    @"icon" : @"lufy.png",
    @"age" : @20,
    @"height" : @"1.55",
    @"money" : @100.9,
    @"sex" : @(SexFemale),
    @"gay" : @"true"
//   @"gay" : @"1"
//   @"gay" : @"NO"
};

// JSON -> User
User *user = [User mj_objectWithKeyValues:dict];

NSLog(@"name=%@, icon=%@, age=%zd, height=%@, money=%@, sex=%d, gay=%d", user.name, user.icon, user.age, user.height, user.money, user.sex, user.gay);
// name=Jack, icon=lufy.png, age=20, height=1.550000, money=100.9, sex=1

JSONString -> Model【JSON字符串转模型】

// 1.Define a JSONString
NSString *jsonString = @"{\"name\":\"Jack\", \"icon\":\"lufy.png\", \"age\":20}";

// 2.JSONString -> User
User *user = [User mj_objectWithKeyValues:jsonString];

// 3.Print user's properties
NSLog(@"name=%@, icon=%@, age=%d", user.name, user.icon, user.age);
// name=Jack, icon=lufy.png, age=20

Model contains model【模型中嵌套模型】

@interface Status : NSObject
@property (copy, nonatomic) NSString *text;
@property (strong, nonatomic) User *user;
@property (strong, nonatomic) Status *retweetedStatus;
@end

/***********************************************/

NSDictionary *dict = @{
    @"text" : @"Agree!Nice weather!",
    @"user" : @{
        @"name" : @"Jack",
        @"icon" : @"lufy.png"
    },
    @"retweetedStatus" : @{
        @"text" : @"Nice weather!",
        @"user" : @{
            @"name" : @"Rose",
            @"icon" : @"nami.png"
        }
    }
};

// JSON -> Status
Status *status = [Status mj_objectWithKeyValues:dict];

NSString *text = status.text;
NSString *name = status.user.name;
NSString *icon = status.user.icon;
NSLog(@"text=%@, name=%@, icon=%@", text, name, icon);
// text=Agree!Nice weather!, name=Jack, icon=lufy.png

NSString *text2 = status.retweetedStatus.text;
NSString *name2 = status.retweetedStatus.user.name;
NSString *icon2 = status.retweetedStatus.user.icon;
NSLog(@"text2=%@, name2=%@, icon2=%@", text2, name2, icon2);
// text2=Nice weather!, name2=Rose, icon2=nami.png

Model contains model-array【模型中有个数组属性,数组里面又要装着其他模型】

@interface Ad : NSObject
@property (copy, nonatomic) NSString *image;
@property (copy, nonatomic) NSString *url;
@end

@interface StatusResult : NSObject
/** Contatins status model */
@property (strong, nonatomic) NSMutableArray *statuses;
/** Contatins ad model */
@property (strong, nonatomic) NSArray *ads;
@property (strong, nonatomic) NSNumber *totalNumber;
@end

/***********************************************/

// Tell MJExtension what type of model will be contained in statuses and ads.
[StatusResult mj_setupObjectClassInArray:^NSDictionary *{
    return @{
               @"statuses" : @"Status",
               // @"statuses" : [Status class],
               @"ads" : @"Ad"
               // @"ads" : [Ad class]
           };
}];
// Equals: StatusResult.m implements +mj_objectClassInArray method.

NSDictionary *dict = @{
    @"statuses" : @[
                      @{
                          @"text" : @"Nice weather!",
                          @"user" : @{
                              @"name" : @"Rose",
                              @"icon" : @"nami.png"
                          }
                      },
                      @{
                          @"text" : @"Go camping tomorrow!",
                          @"user" : @{
                              @"name" : @"Jack",
                              @"icon" : @"lufy.png"
                          }
                      }
                  ],
    @"ads" : @[
                 @{
                     @"image" : @"ad01.png",
                     @"url" : @"http://www.ad01.com"
                 },
                 @{
                     @"image" : @"ad02.png",
                     @"url" : @"http://www.ad02.com"
                 }
             ],
    @"totalNumber" : @"2014"
};

// JSON -> StatusResult
StatusResult *result = [StatusResult mj_objectWithKeyValues:dict];

NSLog(@"totalNumber=%@", result.totalNumber);
// totalNumber=2014

// Printing
for (Status *status in result.statuses) {
    NSString *text = status.text;
    NSString *name = status.user.name;
    NSString *icon = status.user.icon;
    NSLog(@"text=%@, name=%@, icon=%@", text, name, icon);
}
// text=Nice weather!, name=Rose, icon=nami.png
// text=Go camping tomorrow!, name=Jack, icon=lufy.png

// Printing
for (Ad *ad in result.ads) {
    NSLog(@"image=%@, url=%@", ad.image, ad.url);
}
// image=ad01.png, url=http://www.ad01.com
// image=ad02.png, url=http://www.ad02.com

Model name - JSON key mapping【模型中的属性名和字典中的key不相同(或者需要多级映射)】

@interface Bag : NSObject
@property (copy, nonatomic) NSString *name;
@property (assign, nonatomic) double price;
@end

@interface Student : 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 (strong, nonatomic) Bag *bag;
@end

/***********************************************/

// How to map
[Student mj_setupReplacedKeyFromPropertyName:^NSDictionary *{
    return @{
               @"ID" : @"id",
               @"desc" : @"description",
               @"oldName" : @"name.oldName",
               @"nowName" : @"name.newName",
               @"nameChangedTime" : @"name.info[1].nameChangedTime",
               @"bag" : @"other.bag"
           };
}];
// Equals: Student.m implements +mj_replacedKeyFromPropertyName method.

NSDictionary *dict = @{
    @"id" : @"20",
    @"description" : @"kids",
    @"name" : @{
        @"newName" : @"lufy",
        @"oldName" : @"kitty",
        @"info" : @[
        		 @"test-data",
        		 @{
            	             @"nameChangedTime" : @"2013-08"
                         }
                  ]
    },
    @"other" : @{
        @"bag" : @{
            @"name" : @"a red bag",
            @"price" : @100.7
        }
    }
};

// JSON -> Student
Student *stu = [Student mj_objectWithKeyValues:dict];

// Printing
NSLog(@"ID=%@, desc=%@, oldName=%@, nowName=%@, nameChangedTime=%@",
      stu.ID, stu.desc, stu.oldName, stu.nowName, stu.nameChangedTime);
// ID=20, desc=kids, oldName=kitty, nowName=lufy, nameChangedTime=2013-08
NSLog(@"bagName=%@, bagPrice=%f", stu.bag.name, stu.bag.price);
// bagName=a red bag, bagPrice=100.700000

JSON array -> model array【将一个字典数组转成模型数组】

NSArray *dictArray = @[
                         @{
                             @"name" : @"Jack",
                             @"icon" : @"lufy.png"
                         },
                         @{
                             @"name" : @"Rose",
                             @"icon" : @"nami.png"
                         }
                     ];

// JSON array -> User array
NSArray *userArray = [User mj_objectArrayWithKeyValuesArray:dictArray];

// Printing
for (User *user in userArray) {
    NSLog(@"name=%@, icon=%@", user.name, user.icon);
}
// name=Jack, icon=lufy.png
// name=Rose, icon=nami.png

Model -> JSON【将一个模型转成字典】

// New model
User *user = [[User alloc] init];
user.name = @"Jack";
user.icon = @"lufy.png";

Status *status = [[Status alloc] init];
status.user = user;
status.text = @"Nice mood!";

// Status -> JSON
NSDictionary *statusDict = status.mj_keyValues;
NSLog(@"%@", statusDict);
/*
 {
 text = "Nice mood!";
 user =     {
 icon = "lufy.png";
 name = Jack;
 };
 }
 */

// More complex situation
Student *stu = [[Student alloc] init];
stu.ID = @"123";
stu.oldName = @"rose";
stu.nowName = @"jack";
stu.desc = @"handsome";
stu.nameChangedTime = @"2018-09-08";

Bag *bag = [[Bag alloc] init];
bag.name = @"a red bag";
bag.price = 205;
stu.bag = bag;

NSDictionary *stuDict = stu.mj_keyValues;
NSLog(@"%@", stuDict);
/*
{
    ID = 123;
    bag =     {
        name = "\U5c0f\U4e66\U5305";
        price = 205;
    };
    desc = handsome;
    nameChangedTime = "2018-09-08";
    nowName = jack;
    oldName = rose;
}
 */

Model array -> JSON array【将一个模型数组转成字典数组】

// New model array
User *user1 = [[User alloc] init];
user1.name = @"Jack";
user1.icon = @"lufy.png";

User *user2 = [[User alloc] init];
user2.name = @"Rose";
user2.icon = @"nami.png";

NSArray *userArray = @[user1, user2];

// Model array -> JSON array
NSArray *dictArray = [User mj_keyValuesArrayWithObjectArray:userArray];
NSLog(@"%@", dictArray);
/*
 (
 {
 icon = "lufy.png";
 name = Jack;
 },
 {
 icon = "nami.png";
 name = Rose;
 }
 )
 */

Core Data

func json2CoreDataObject() {
    context.performAndWait {
        let object = MJCoreDataTester.mj_object(withKeyValues: Values.testJSONObject, context: context)
        // use the object
    }
}

func coreDataObject2JSON() {
    context.performAndWait {        
        let dict = coreDataObject.mj_keyValues()
        // use dict
    }
}

Coding (Archive & Unarchive methods are deprecated in iOS 12)

#import "MJExtension.h"

@implementation MJBag
// NSCoding Implementation
MJCodingImplementation
@end

/***********************************************/

// what properties not to be coded
[MJBag mj_setupIgnoredCodingPropertyNames:^NSArray *{
    return @[@"name"];
}];
// Equals: MJBag.m implements +mj_ignoredCodingPropertyNames method.

// Create model
MJBag *bag = [[MJBag alloc] init];
bag.name = @"Red bag";
bag.price = 200.8;

NSString *file = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop/bag.data"];
// Encoding by archiving
[NSKeyedArchiver archiveRootObject:bag toFile:file];

// Decoding by unarchiving
MJBag *decodedBag = [NSKeyedUnarchiver unarchiveObjectWithFile:file];
NSLog(@"name=%@, price=%f", decodedBag.name, decodedBag.price);
// name=(null), price=200.800000

Secure Coding

Using MJSecureCodingImplementation(class, isSupport) macro.

@import MJExtension;

// NSSecureCoding Implementation
MJSecureCodingImplementation(MJBag, YES)

@implementation MJBag
@end

 /***********************************************/

// what properties not to be coded
[MJBag mj_setupIgnoredCodingPropertyNames:^NSArray *{
    return @[@"name"];
}];
// Equals: MJBag.m implements +mj_ignoredCodingPropertyNames method.

// Create model
MJBag *bag = [[MJBag alloc] init];
bag.name = @"Red bag";
bag.price = 200.8;
bag.isBig = YES;
bag.weight = 200;

NSString *file = [NSTemporaryDirectory() stringByAppendingPathComponent:@"bag.data"];

NSError *error = nil;
// Encoding by archiving
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:bag requiringSecureCoding:YES error:&error];
[data writeToFile:file atomically:true];

// Decoding by unarchiving
NSData *readData = [NSFileManager.defaultManager contentsAtPath:file];
error = nil;
MJBag *decodedBag = [NSKeyedUnarchiver unarchivedObjectOfClass:MJBag.class fromData:readData error:&error];
MJExtensionLog(@"name=%@, price=%f", decodedBag.name, decodedBag.price);

Camel -> underline【统一转换属性名(比如驼峰转下划线)】

// Dog
#import "MJExtension.h"

@implementation Dog
+ (NSString *)mj_replacedKeyFromPropertyName121:(NSString *)propertyName
{
    // nickName -> nick_name
    return [propertyName mj_underlineFromCamel];
}
@end

// NSDictionary
NSDictionary *dict = @{
                       @"nick_name" : @"旺财",
                       @"sale_price" : @"10.5",
                       @"run_speed" : @"100.9"
                       };
// NSDictionary -> Dog
Dog *dog = [Dog mj_objectWithKeyValues:dict];

// printing
NSLog(@"nickName=%@, scalePrice=%f runSpeed=%f", dog.nickName, dog.salePrice, dog.runSpeed);

NSString -> NSDate, nil -> @""【过滤字典的值(比如字符串日期处理为NSDate、字符串nil处理为@"")】

// Book
#import "MJExtension.h"

@implementation Book
- (id)mj_newValueFromOldValue:(id)oldValue property:(MJProperty *)property
{
    if ([property.name isEqualToString:@"publisher"]) {
        if (oldValue == nil) return @"";
    } else if (property.type.typeClass == [NSDate class]) {
        NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
        fmt.dateFormat = @"yyyy-MM-dd";
        return [fmt dateFromString:oldValue];
    }

    return oldValue;
}
@end

// NSDictionary
NSDictionary *dict = @{
                       @"name" : @"5分钟突破iOS开发",
                       @"publishedTime" : @"2011-09-10"
                       };
// NSDictionary -> Book
Book *book = [Book mj_objectWithKeyValues:dict];

// printing
NSLog(@"name=%@, publisher=%@, publishedTime=%@", book.name, book.publisher, book.publishedTime);

NSDate -> NSString【模型转字典时, 修改 Date 类型至 String】

- (void)mj_objectDidConvertToKeyValues:(NSMutableDictionary *)keyValues {
    // NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // formatter.dateFormat = @"yyy-MM-dd";
    // should use sharedFormatter for better performance  
    keyValues[@"publishedTime"] = [sharedFormatter stringFromDate:self.publishedTime];
}

More use cases【更多用法】

  • Please reference to NSObject+MJKeyValue.h and NSObject+MJCoding.h

期待

  • 如果在使用过程中遇到BUG,希望你能Issues我,谢谢(或者尝试下载最新的框架代码看看BUG修复没有)
  • 如果在使用过程中发现功能不够用,希望你能Issues我,我非常想为这个框架增加更多好用的功能,谢谢
  • 如果你想为MJExtension输出代码,请拼命Pull Requests我

mjextension's People

Contributors

100mango avatar 520dev avatar awesomejue avatar banchichen avatar chaoyuan899 avatar codermjlee avatar daviskoh avatar elfsundae avatar harley-xk avatar isunimp avatar jianing93 avatar kinarobin avatar lawrencehan avatar neeeo avatar sarieltang avatar shutup avatar sunkehappy avatar veinguo avatar wenchaod avatar willey-l avatar wolfcon avatar yaannz avatar zaggerwang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mjextension's Issues

支持 mj 大大

字段中有BOOL值时解析失败

MJ老师,我开始把你这个框架用到了我现在开发的一个项目中,发现在解析服务器返回的布尔字段时出错,我的实体类中字段类型是BOOL

有崩溃问题,杰哥能否处理下?或者解析下原因呢

杰哥,请看截图哈,好像说什么no summary

我有一个方法需要判断表是否自动创建,如果没有创建成功,那么就使用MJExtension不停的重复工作,直到表创建成功,所以在短时间内(我设的是0.1f调用一次MJExtension的成员变量遍历)大量重复调用MJExtension。

卡死行:_cachedTypes[code] = type;//卡死在这里,系统自行打了一个断点,且无法跳过此断点
原因: 未知,,大概原因是多次高速调用MJIvar(业务需求,我必须这么做),读取成员属性造成的。

我暂时的解决土办法:高速调用时间周期为0.1秒,我试过周期越大,崩溃的概率越小,设为2秒调用一次,崩溃很少,但是还是偶尔有,且业务受到影响。

MJType *type = _cachedTypes[code]; //卡死在此行,不能过掉
断点查看code = @"@"NSString"",有时候崩溃这个code又是正常的,但是会出现no summary(如图)。

报错信息:
CoreFMDBModel(2901,0x1198e9000) malloc: *** error for object 0x7fd099703c70: double free
*** set a breakpoint in malloc_error_break to debug

3

28cfea65-5c42-4f5e-b0ac-75e44583fbc4

还有这里也会崩溃,这些崩溃查看里面的变量,好像都是正常的,
1
下面这个是左侧的线程信息:
2

上面两个都不是正常的崩溃,是卡死在这个地方,不能过掉。

进行多级映射的时候,上一级必须有对应的值,否则奔溃

你好,MJ 老师
在项目中使用这个框架的时候,发现一个小问题: 进行多级映射的时候,json数据中必须有对应的值,否则会奔溃。
我将您的示例demo 做了修改,用来复现BUG,您可以看看。
void keyValues2object4()
{
// 1.定义一个字典
NSDictionary *dict = @{
@"id" : @"20",
@"desciption" : @"好孩子",
@"name" : [NSNull null],
@"other" : @{
@"bag" : @{
@"name" : @"小书包",
@"price" : @100.7
}
}
};

// 2.将字典转为Student模型
Student *stu = [Student objectWithKeyValues:dict];

——————————此处crash
}

"oldName" : @"name.oldName",
在Student 类中对 oldName进行了name.oldName的多级映射, 但是如果上一级name ==null 则就直接奔溃。

在我的项目中的实际场景是 @"赠送人" : @{@”赠送人ID“,@”赠送人姓名“}
如果赠送人都不存在, 那么“赠送人”=nul,进行赠送人ID 和赠送人姓名,映射解析的时候就奔溃了。

含有UIImage成员对象,闪退崩溃

MJ哥,
如果一个对象含有UIImage对象,然后调用keyValues,模型转字典,直接报错?
能不能添加一些成员属性不需要转字典的功能??

关于replacedKeyFromPropertyName使用后的bug

不知道是不是我的需求比较特别,使用过程中有以下两点问题:
1、子类中要实现replacedKeyFromPropertyName要先获取父类中的replacedKeyDict再拼接上自己要替换的属性,否则父类中的replacedKeyFromPropertyName会被覆盖掉?
2、当子类中实现replacedKeyFromPropertyName要替换掉父类属性对应的key时,缓存机制cachedIvarWithIvar 和 MJCachedIvarsKey 工作就会出现问题。

最后,忍不住要夸一下,这套框架很棒~ 用着非常爽~

模型中的属性名和字典中的key映射问题

对于这个问题,readme里说的是单独调用setupReplacedKeyFromPropertyName:方法来实现,看了一下Example是放在MJExtensionConfig类里的load方法里调用,只会调用一次,实现很巧妙,但是还是有不足:映射与Model类分离。觉得把这个映射放在Model类里不是更好吗,比如放在Model类的+load方法中?或者用其它的函数?
如果方法可取建议更新readme

建議創建 podspec

方便 cocoapods 管理,即使不上傳到 cocoapods,我也能 fork 一下

pod search MJExtension

添加依赖的时候一直卡在Analyzing dependencies,pod search MJExtension,发现找不到, Unable to find a pod with name matching `MJExtension'。另一个MJRefresh也同样找不到。

JSON value is empty

Hi,

If a value in my JSON dictionary is an empty string, MJExtension fires an exception in the class MJIVar in the method - (void)setValue:(id)value forObject:(id)object.

I thought if any value is an empty string, it will set the model property as empty string.

Thank you for your hard efforts.

MJ老师,如何把不同接口返回的不同字段名,赋值给同一个Model的某个属性呢

MJ老师,如何把不同接口返回的不同字段名,赋值给同一个Model的某个属性呢?

比如有个模型User,有个属性userId,有多个地方需要用到这个模型,
服务器2个不同接口,其中一个返回 {“userId” : "132"},另一个返回的是{"commentUserId" : "132"}

用这个也没法解决呀

  • (NSDictionary *)objectClassInArray {
    return @{@"userId": @“commentUserId”};
    }

我该怎么处理这种问题?

不吝赐教~

丢失精度

杰哥,字典里value的值是double类型时。转成模型会丢失精度,变成整形。

混编c++的时候,导入框架编译报错

在NSObject+MJvar.m文件中 公共类方法+ (instancetype)tempObject 报错 static const char MJTempObjectKey; 提示信息:Default initalization of an object of const type 'const char'
编译器为:Default compiler (Apple LLVM 6.0)

老师,数组里面存放的都是Item字符串,怎么赋值?

        <key>name</key>
        <string>北京</string>
        <key>sub</key>
        <array>
            <dict>
                <key>name</key>
                <string>北京市</string>
                <key>sub</key> //<--请问下这里怎么赋值 -->
                <array>
                    <string>东城区</string>
                    <string>西城区</string>
                    <string>崇文区</string>
                    <string>宣武区</string>
                    <string>朝阳区</string>
                    <string>丰台区</string>
                    <string>石景山区</string>
                    <string>海淀区</string>
                    <string>门头沟区</string>
                    <string>房山区</string>
                    <string>通州区</string>
                    <string>顺义区</string>
                    <string>昌平区</string>
                    <string>大兴区</string>
                    <string>怀柔区</string>
                    <string>平谷区</string>
                    <string>密云县</string>
                    <string>延庆县</string>
                    <string>其他区</string>
                </array>
                <key>zipcode</key>
                <string>100000</string>
            </dict>
        </array>

在做三级联动,最后的区域是字符串,不知道怎么赋值了,直接创建一个NSArray *sub 是空值。

import <Foundation/Foundation.h>

@interface areaModel : NSObject

@Property (nonatomic, strong) NSArray *sub;

@EnD

你好,怎么生成的字典怎么转json

使用JSONKit ,NSLog(@"%@", [dict JSONData]); NSLog(@"%@", [dict JSONString]); 结果都未null。

[NSJSONSerialization dataWithJSONObject:[NSDictionary dictionaryWithDictionary:dict] options:NSJSONWritingPrettyPrinted error:nil];
提示Invalid type in JSON write (__NSDate)

NSSet转换失败了

在使用coredata的时候,系统会在生成的model中选择nsset ,像这种在转化的时候
@Property (nonatomic, retain) NSSet *marks;
这种怎么告诉MJExtension,marks里存放的是什么模型呢?

字符编码问题

BOOL这个类型字符啊编码不一定是c,32位和64位下是不一样的

keyValues的类型为id和NSDictionary,混淆

方法:objectWithKeyValues:(NSDictionary *)keyValues error:(NSError *__autoreleasing *)error
方法二:objectWithKeyValues:(id)keyValues context:(NSManagedObjectContext *)context error:

MJ老师,对于keyValues的类型,,有的方法是写的NSDictionary,有的地方是id类型,二暴露在外边的是NSDictionary,,有时候传参是string等等,,虽然方法上面没有大问题,但是这样会不会造成用户的混淆,不统一?O(∩_∩)O谢谢

objectArrayWithKeyValuesArray返回类型

  • (NSArray *)objectArrayWithKeyValuesArray:(NSArray *)keyValuesArray error:(NSError *__autoreleasing *)error

内部实现返回的是NSMutableArray,那么返回类型为什么不写成NSMutableArray?

json数据转换为model时候出现错误

[__NSCFConstantString objectArrayWithKeyValuesArray:]: unrecognized selector sent to instance 0x10012d848

NSObject+MJKeyValue 第125行
Class objectClass = [ivar objectClassInArrayFromClass:[self class]];
if (objectClass) {
// 3.字典数组-->模型数组
value = [objectClass objectArrayWithKeyValuesArray:value];
}

调用直接报错。

@Property (strong,nonatomic) NSMutableArray * topic;

数据:
{"data":{"topic":[{"tid":2154829,"author":"\u5443\u5443\u5443\u989d\u989d\u989d","authorid":15498192,"subject":"\u82e6\u903c\u7684\u6708\u5b50\u7ec8\u4e8e\u8981\u7ed3\u675f\u4e86\uff01\u5410\u69fd\u90a3\u4e9b\u70e6\u5fc3\u4e8b\uff01"},{"tid":2141234,author":"xin206","authorid":11252235,"subject":"\u90fd\u6765\u8bf4\u8bf4\u5b9d\u5b9d\u662f\u8ddf\u81ea\u5df1\u7761\u8fd8\u662f\u5a46\u5a46\u7761"},{"tid":2126980,"author":"Babyface212","authorid":14429965,"subject":"\u6709\u6ca1\u6709\u52c7\u6c14\u6652\u6652\u4f60\u7684\u6708\u5b50\u7167\uff01"}]},"errmsg":{"errno":0,"msg":""},"status":1}

对id类型的支持

非常感谢开源这么好的库。在改用此库的过程中,有一些类是有id类型的成员变量(可能是某个自定义的model), 这个id类型是根据业务需求来变化的。 可否提供一个类似的方法:

@Property (strong, nonatomic) id user;

  • (NSDictionary *) classNameForId {

    if (_type == AdminUserType) {
    return @{@"user" : [AdminUser class]};
    }
    return @{@"user" : [GeneralUser class]};
    }

这样以便提供id类型在model与dictionary之间互转的时候是根据正确的类型来转换的。

字典转模型有BUG

明杰老师,这个字典转模型有BUG:

  • (instancetype)objectWithKeyValues:(NSDictionary *)keyValues
    {
    // if ([keyValues isKindOfClass:[NSNull class]]){
    // return nil;
    // }

    NSString *desc = [NSString stringWithFormat:@"keyValues is not a NSDictionary - keyValues参数不是一个字典, keyValues is a %@ - keyValues参数是一个%@", keyValues.class, keyValues.class];
    MJAssert([keyValues isKindOfClass:[NSDictionary class]], desc);

    id model = [[self alloc] init];
    [model setKeyValues:keyValues];
    return model;
    }

返回的数据中假如有:
"name": null

编译时:
keyValues = NSNull
就会报错。。。我觉得应该返回nil

NSString -> BOOL, 结果不都对

我的JSON文件像这样
{
"online" : "yes" or "online" : "true"
}

低于iPhone5s 机器上面, 结果是 online = NO;
iPhone5s之后,包含iPhone5s, 结果是 online = YES;

这样看来是arm64的结果是正常的,armv7, armv7s都不正常,请查看,谢谢!

有个问题,麻烦老师有空看下

MJ Teacher:
您好,对于你的这个新方法
// 新方法更加没有侵入性和污染

  • (NSDictionary *)objectClassInArray
    {
    return @{
    @"statuses" : @"Status",
    @"ads" : @"Ad"
    };
    }
    我想问,这个模型能作为参数传进来吗?
    因为我服务器返回的是这样的json数据,{"code" : 1, "msg" : null, "obj" : [{"id" : 1, "name" : "张三"},{"id" : 2, "name" : "李四"}] } 这里的obj 对象是动态的,可能是集合List,也可能是个对象, 字段不一,如何将这个JSON 转成对象模型呢?

How to handle a typedef enum property?

Hi, MJ

I came across a problem:
if there is a property named:

@Property (nonatomic, assign)ZC_SchemeCategory category;

which is a enum:

typedef enum{

ZC_SchemeCategoryMusic,

}ZC_SchemeCategory;

how could I tell the extension to handle it ?

thanks!

给MJ提几个建议哈,

1.MJIvar里面的遍历,可以增加一个idx索引。
2.我的同事写的接口有id,class字段,或者select等字段,为了不冲突就用了大写(有的有大小写,有的纯小写),希望增加大小写支持。
我手动改过你的代码,先直接匹配,如果没有就转为纯小写匹配。

谢谢,留个名吧,成都 charlin 华西都市网

这个是我写的,呵呵https://github.com/nsdictionary/CoreRefresh

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

在这种情况下,直接写
[StatusResult setupObjectClassInArray:^NSDictionary *{
return @{
@"statuses" : @"Status",
@"ads" : @"Ad"
};
}]; 是成功的;但是如果我在.m文件中写成

  • (NSDictionary *)objectClassInArray{
    return @{
    @"statuses" : [Status class],
    @"ads" : [Ad class]
    }; 就失败了, 得到的status数据是字典形式的,而不是模型数据了。

请问MJ老师该类库是否支持MRC?

我在一个历史遗留的MRC的项目中使用MJExtension时,会在MJFoundation的+ (BOOL)isClassFromFoundation:(Class)c中crash掉,错误信息是:EXC_BAD_ACCESS(code=1, address=0x88180018)。请问是不支持MRC的项目么?或是在MRC的项目中需要注意什么问题呢?
谢谢MJ老师!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.