iOS:OCMapper:从json中反序列化日期

本文关键字:反序列化 日期 OCMapper iOS json | 更新日期: 2023-09-27 18:06:24

我集成了OCMapper,用于将json字符串转换为自定义模型对象。我无法反序列化日期对象。例如,我有一个json,如

NSString* sampleOutput=@"{'"UserType'":'"Admin'",'"testdate'":'"/Date(1438545600000+0400)/'"}";
NSData* sampleDate= [sampleOutput dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *loginDictionary = [NSJSONSerialization JSONObjectWithData:sampleDate options:NSJSONReadingAllowFragments error:&responseError];
MyModel* loginResponse= [[ObjectMapper sharedInstance] objectFromSource:loginDictionary toInstanceOfClass:[MyModel class]];

My Model类结构是

`@interface MyModel : NSObject
@property(nonatomic,strong) NSString* userType;
@property(nonatomic,strong) NSDate* testdate;
@end`

但是我得到了testdate对象的nil值。请告诉我最好的方法。

如果json是

 NSString* sampleOutput=@"{'"UserType'":'"Admin'",'"testdate'":'"2015-08-05'"}";

我可以通过InCodeMappingProvider

解析日期

InCodeMappingProvider *inCodeMappingProvider = [[InCodeMappingProvider alloc] init];
        NSDateFormatter *dateOfBirthFormatter = [[NSDateFormatter alloc] init];
        [dateOfBirthFormatter setDateFormat:@"yyyy-dd-MM"];
        [inCodeMappingProvider setDateFormatter:dateOfBirthFormatter forPropertyKey:@"testdate" andClass:[MyModel class]];
        [[ObjectMapper sharedInstance] setMappingProvider:inCodeMappingProvider];

但是我需要转换特定的c#日期序列化格式NSString* sampleOutput=@"{'"UserType'":'"Admin'",'"testdate'":'"/Date(1438545600000+0400)/

iOS:OCMapper:从json中反序列化日期

我终于找到了答案。

在objectmap

。m-> processDictionary:

// Convert NSString to NSDate if needed
                    if ([propertyTypeString isEqualToString:@"NSDate"])
                    {
                        if ([value isKindOfClass:[NSDate class]])
                        {
                            nestedObject = value;
                        }
                        else if ([value hasPrefix:@"/Date("]){
                            nestedObject = [self myCustomDateConversion:value];
                        }
                        else if ([value isKindOfClass:[NSString class]])
                        {
                            nestedObject = [self dateFromString:value forProperty:propertyName andClass:class];
                        }
                    }