我正在使用RestKit处理我的所有JSON响应。其中一个对象是日期,但它不是使用标准格式,而是一个带有日,月,年参数的对象......
{
"date": {
"day": 30,
"month": 7,
"year": 2014
}
}
如何构建RKMapping
或RKValueTransformer
来将其映射到NSDate
对象?
答案 0 :(得分:0)
这是我最终使用的内容。
RKValueTransformer *dateTransformer = [RKBlockValueTransformer valueTransformerWithValidationBlock:^BOOL(__unsafe_unretained Class sourceClass, __unsafe_unretained Class destinationClass) {
return ([sourceClass isSubclassOfClass:[NSDictionary class]] && [destinationClass isSubclassOfClass:[NSDate class]]);
} transformationBlock:^BOOL(id inputValue, __autoreleasing id *outputValue, Class outputValueClass, NSError *__autoreleasing *error) {
RKValueTransformerTestInputValueIsKindOfClass(inputValue, [NSDictionary class], error);
RKValueTransformerTestOutputValueClassIsSubclassOfClass(outputValueClass, [NSDate class], error);
NSDateComponents *dc = [[NSDateComponents alloc] init];
dc.day = [inputValue[@"day"] integerValue];
dc.month = [inputValue[@"month"] integerValue];
dc.year = [inputValue[@"year"] integerValue];
dc.calendar = [NSCalendar currentCalendar]; // This step is easy to forget.
NSDate *aDate = dc.date;
*outputValue = aDate;
return YES;
}];
实际使用这个变压器...
[[RKValueTransformer defaultValueTransformer] addValueTransformer:dateTransformer];