NSInvalidArgumentException,原因:'JSON写入中的无效types(__NSDate)'

我收到这个exception,当我尝试JSON编码NSDate对象。我相信NSDate是不兼容的JSON编码。 但我必须编码的date。任何解决scheme?

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSDate)' 

首先将数据存储在NSString中。 然后将您的string转换为NSDate。

你可以参考SO:

将NSString转换为NSDate(并返回)

NSString到NSDate的转换问题

如何使用NSDateFormatter将NSString转换为NSDate?

转换NSDate到NSString并尝试编码。

 - (NSString *) changeDateToDateString :(NSDate *) date { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setTimeZone:[NSTimeZone localTimeZone]]; NSLocale *locale = [NSLocale currentLocale]; NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:@"hh mm" options:0 locale:locale]; [dateFormatter setDateFormat:dateFormat]; [dateFormatter setLocale:locale]; NSString *dateString = [dateFormatter stringFromDate:date]; return dateString; } 

如上所述,您必须先将您的NSDate转换为NSString。 但是,现在还不清楚date应该用哪种格式表示。答案可以在这里find:“JSON本身并没有指定如何表示date,但是JavaScript是”ISO8601“。

这是一个来自NSDate的帮助类别的ISO8601转换方法,由Erica Sadun提供 :

 - (NSString *)ISO8601 { struct tm time; time_t interval = [self timeIntervalSince1970]; gmtime_r(&interval, &time); char *x = calloc(1, 21); strftime_l(x, 20, "%FT%TZ", &time, gmtlocale); NSString *string = [NSString stringWithUTF8String:x]; free(x); return string; } 

如果你得到一个ISO8601string回到JSON有效载荷中,并且想把它转换成一个NSDate,那么对NSDate使用这个类方法:

 + (NSDate *)dateFromISO8601:(NSString *)string { if(!string) return nil; if (![string isKindOfClass:[NSString class]]) return nil; struct tm time; strptime_l([string UTF8String], "%FT%TZ", &time, gmtlocale); return [NSDate dateWithTimeIntervalSince1970:timegm(&time)]; } 

你有没有尝试过 ?

 updateDate = [NSNumber numberWithFloat:[[NSDate date] timeIntervalSince1970]]; 

如上所述: SDK不支持NSDate对象

遵循以下步骤:

1.以JSON格式转换date:

  NSDateFormatter *formatter = [[[NSDateFormatter alloc] init]autorelease]; [formatter setDateFormat:@"Z"]; NSString *updateDate = [NSString stringWithFormat:@"/Date(%.0f000%@)/", [[NSDate date] timeIntervalSince1970],[formatter stringFromDate:[NSDate date]]]; 

2.embedded在一些数组中并POST数组。

在JSON中存储和检索NSDate对象最简单的方法是使用NSDate的timeIntervalSince1970属性。

返回的NSTimeInterval(double)是非常标准的,可以很容易地使用以下方法转换回NSDate对象:

 NSDate dateWithTimeIntervalSince1970:<#(NSTimeInterval)#> 

在尝试对date进行编码之前,您必须将date转换为string。 到处都有足够的例子,所以应该很容易find

对于我们的情况,我们正在使用地幔将对象转换为JSON,而我们的一个对象的属性NSDate缺less其JSONTransformer

 @property (nonatomic) NSDate *expiryDate; 

哪里:

 + (NSValueTransformer *)expiryDateJSONTransformer { 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]; }]; } + (NSDateFormatter *)dateFormatter { NSDateFormatter *df = [NSDateFormatter new]; df.dateFormat = @"yyyy-MM-dd"; return df; }