NSInvalidArgumentException, reason: 'Invalid type in JSON write (__NSDate)'



当我尝试JSON编码NSDate对象时,我得到了这个异常。我认为NSDate不兼容JSON编码。但我必须对日期进行编码。有解决方案吗?

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

首先将数据存储在NSString中。然后将字符串转换为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。然而,目前还不清楚日期应该以哪种格式表示。答案可以在这里找到:"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;
}

如果你得到一个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)];
}

你试过了吗?

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

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

1。将日期转换为JSON格式:

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

2。

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

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

NSDate dateWithTimeIntervalSince1970:<#(NSTimeInterval)#>

在尝试对日期进行编码之前,必须将日期转换为字符串。到处都有足够多的例子,所以应该很容易找到

对于我们的情况,我们使用Mantle将对象转换为JSON,其中一个具有NSDate属性的对象缺少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;
}

我在我的body params encoder

// handle dates
              var _params = [String: Any]()
              params.forEach { (key, value) in
                if let date = value as? Date {
                    _params[key] = DateFormatter.iso8601Full.string(from: date)
                } else {
                    _params[key] = value
                }
              }
              return try? JSONSerialization.data(withJSONObject: _params)