利用MJExtension框架将Model转化为JsonString时
第一步:将Model转化为JsonObject,也就是字典,必须是系统自带的类NSString、NSNumber、NSDictionary、NSArray、NSNull的对象,转化之后不能包含任何的自定义model,否则会报错;
crash在
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
错误信息:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (HDSanitationInstallPositionModel)'
原因:model不能直接转成json
能够转换为json字符串的对象必须具有如下属性:
顶层对象必须是NSArray或者NSDictionary
所有的对象必须是NSString/NSNumber/NSArray/NSDictionary/NSNull的实例, 所有NSDictionary的key必须是NSString类型, 数字对象不能是非数值或无穷.
当前顶层model的属性结构是这样的:
排查发现HDSanitationInstallPositionModel这个类的属性里面有个自定义的superModel,可以在model--->字典的过程中忽略此属性:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class HDMeasureInfoModel,HDSanitationInstallInfoModel;
@interface HDSanitationInstallPositionModel : NSObject <NSCoding>
@property (nonatomic,copy) NSString * name;
/** HDMeasureInfoModel数组 */
@property (nonatomic,strong) id deviceInstallImage;
@property (nonatomic,strong) HDSanitationInstallInfoModel * superModel;
@property (nonatomic,assign,getter=isSaved) BOOL saved;
@property (nonatomic,assign) NSInteger index;
@property (nonatomic,assign) BOOL isShow;
@end
NS_ASSUME_NONNULL_END
可以利用MJExtension框架自带的协议在model--->字典过程中忽略它:
#import "HDSanitationInstallPositionModel.h"
@implementation HDSanitationInstallPositionModel
+ (NSDictionary *)mj_objectClassInArray{
return @{@"deviceInstallImage":@"HDMeasureInfoModel"};
}
+ (NSArray *)mj_ignoredPropertyNames{
return @[@"superModel"];
}
第二步:将第一步转化后的JsonObject转化为JsonString.
[[param.carRecord mj_JSONObject] mj_JSONString];