json格式:
NSDictionary *dict = @{
@"name": @"Bob",
@"cars": @[
@{ @"make":@"ford",
@"year": @"1972" },
@{ @"make": @"mazda",
@"year": @"2000" }
],
@"owner":@{
@"name":@"arthur",
@"gender":@"male",
@"age": @101,
},
@"date":@"2015-09-02"
};
//.h#import "MTLModel.h"
#import <Mantle.h>
@interface CarModel : MTLModel<MTLJSONSerializing>
@property (nonatomic, copy) NSString *make;
@property (nonatomic, copy) NSString *year;
@end
@interface Owner : MTLModel<MTLJSONSerializing>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, copy) NSString *gender;
@property (nonatomic) NSInteger age;
@end
@interface TestModel : MTLModel<MTLJSONSerializing>
@property (nonatomic, copy) NSString *name;
@property (nonatomic, strong) NSArray *cars;
@property (nonatomic, strong) Owner *owner;
@property (nonatomic, copy) NSString *ownername;
@property (nonatomic, copy) NSString *maker;
@end
#import "TestModel.h"
@implementation CarModel
+ (NSDictionary *)JSONKeyPathsByPropertyKey{
return @{@"make":@"make",@"year":@"year"};
}
@end
@implementation Owner
+ (NSDictionary*)JSONKeyPathsByPropertyKey{
return @{@"name":@"name",
@"gender":@"gender",@"age":@"age",
};
}
@end
@implementation TestModel
//指向一个array的映射
+ (NSValueTransformer *)carsJSONTransformer {
return [MTLJSONAdapter arrayTransformerWithModelClass:CarModel.class];
}
//指向一个dict的映射
+ (NSValueTransformer*)ownerJSONTransformer{
return [MTLJSONAdapter dictionaryTransformerWithModelClass:Owner.class];
}
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
@"name":@"name",
@"cars":@"cars",
@"owner":@"owner",
@"ownername":@"owner.name",
@"maker":@"cars",
};
}
//找出cars下第一个item的make
+ (NSValueTransformer *)makerJSONTransformer {
return [MTLValueTransformer transformerUsingForwardBlock:^id(NSArray *cars, BOOL *success, NSError **error) {
return [cars.firstObject valueForKey:@"make"];
}];
}
开始解析:
NSError *error;
TestModel *tm = [MTLJSONAdapter modelOfClass:[TestModel class] fromJSONDictionary:dict error:&error];
NSLog(@"%@",tm);
CarModel *car = [tm.cars objectAtIndex:1];
NSLog(@"%@",car.make);
Owner *owner = tm.owner;
NSLog(@"%@",owner.name);
NSLog(@"%@",tm.ownername);//直接取子类别下数据