Har*_*nan 22 iphone json nsdate ios
当我尝试JSON编码NSDate对象时,我得到了这个异常.我相信NSDate与JSON编码不兼容.但我必须编码日期.任何解决方案?
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSDate)'
Run Code Online (Sandbox Code Playgroud)
Rus*_*shi 12
首先将您的数据存储在NSString中.然后将您的字符串转换为NSDate.
你可以参考SO:
如何使用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;
}
Run Code Online (Sandbox Code Playgroud)
如前所述,您必须首先将 NSDate 转换为 NSString。然而,目前还不清楚日期应该以哪种格式表示。答案可以在这里找到:“JSON 本身没有指定如何表示日期,但 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;
}
Run Code Online (Sandbox Code Playgroud)
如果您在 JSON 负载中返回 ISO8601 字符串并希望将其转换为 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)];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29083 次 |
| 最近记录: |