Mantle如何将数组里面的几个元素映射到不同的属性上呢?
现在我接收到的JSON是这样的
{
"data" : [
0.26,
0.03,
24.22,
16.15,
16.15
],
"status" : true,
"text" : ""
}
我需要用mantle将data里面的5个数组映射到model上的5个属性。比如这样:
@property(nonatomic,copy)NSNumber * firstNum;
@property(nonatomic,copy)NSNumber * secondNum;
@property(nonatomic,copy)NSNumber * thirdNum;
@property(nonatomic,copy)NSNumber * fourthnum;
@property(nonatomic,copy)NSNumber * fifthNum;
@property(nonatomic,copy)NSString * text;
@property(nonatomic)BOOL status;
然后我在网上查到了这样一个方法
+ (NSValueTransformer *)pointListJSONTransformer
{
return [MTLValueTransformer transformerWithBlock:^id(NSArray *array) {
return [array firstObject];
}];
}
这样可以将某个数组的的单个元素拿出来作为属性
但是我现在有多个,那到底应该怎么做呢
梨花酱的胖次
9 years, 7 months ago
Answers
你需要2个模型
.h 文件
@interface HLModelDataInfo : MTLModel<MTLJSONSerializing>
@property(nonatomic,copy)NSNumber * firstNum;
@property(nonatomic,copy)NSNumber * secondNum;
@property(nonatomic,copy)NSNumber * thirdNum;
@property(nonatomic,copy)NSNumber * fourthnum;
@property(nonatomic,copy)NSNumber * fifthNum;
@end
@interface HLModelData : MTLModel<MTLJSONSerializing>
@property (strong, nonatomic) HLModelData *data;
@property (assign, nonatomic) BOOL status;
@property (strong, nonatomic) NSString *text;
@end
.m文件中你除了实现协议外 再实现一个映射到数组的NSValueTransformer
+ (NSValueTransformer *)dataJSONTransformer{
return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass:HLModelDataInfo.class];
}
skfool
answered 9 years, 7 months ago