添加mantle 到你的项目1. pod search mantle 2. git上去下
会用cocoapod应该都会的, 我就不详细说了, 如果不会的可以百度, 或者留言, 教你也可以
好进入正题
//
// Model.h
// BlockDemo
//
// Created by 胡岩 on 15/10/28.
// Copyright (c) 2015年 胡岩. All rights reserved.
//
#import "MTLModel.h"
@interface Model : MTLModel
@property (nonatomic, strong) NSDate *date;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *gender;
@end
//
// Model.m
// BlockDemo
//
// Created by 胡岩 on 15/10/28.
// Copyright (c) 2015年 胡岩. All rights reserved.
//
#import "Model.h"
#import <Mantle.h>
@interface Model ()<MTLJSONSerializing>
@end
@implementation Model
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
return @{
@"date" : @"date",
@"name" : @"name",
@"gender" : @"gender"
};
}
+ (NSDateFormatter *)dateFormatter {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss'Z'";
return dateFormatter;
}
// 这里<span style="font-family: Arial, Helvetica, sans-serif;">dateJSONTransformer 假如你.h文件里面的NSDate 变量叫todayDate 那么就要把</span><span style="font-family: Arial, Helvetica, sans-serif;">dateJSONTransformer改成todayD</span><span style="font-family: Arial, Helvetica, sans-serif;">ateJSONTransformer</span><span style="font-family: Arial, Helvetica, sans-serif;"></span><div>
</div>
+ (NSValueTransformer *)dateJSONTransformer
{
return [MTLValueTransformer transformerUsingForwardBlock:^id(NSString *dateString, BOOL *success, NSError *__autoreleasing *error) {
return [self.dateFormatter dateFromString:dateString];
} reverseBlock:^id(NSDate *date, BOOL *success, NSError *__autoreleasing *error) {
return [self.dateFormatter stringFromDate:date];
}];
}
- (instancetype)initWithDictionary:(NSDictionary *)dictionaryValue error:(NSError *__autoreleasing *)error {
self = [super initWithDictionary:dictionaryValue error:error];
if (self == nil) {
return nil;
}
return self;
}
使用
NSDictionary *dic = [NSDictionary dictionary];// 你要解析的字典
Model *model = [MTLJSONAdapter modelOfClass:[Model class] fromJSONDictionary:dic error:nil];
// 使用就是这样
model.name
ok基本的使用就这么多, 更多的可以去读官方文档, 很好使用的