ios NSInvalidArgumentException,原因:'JSON 写入中的无效类型(__NSDate)'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14337419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
NSInvalidArgumentException, reason: 'Invalid type in JSON write (__NSDate)'
提问by Harikrishnan
I'm getting this exception when I try to JSON encode NSDate object.I believe NSDate is not compatible for JSON encoding. but I must encode the date.Any solutions?
当我尝试对 NSDate 对象进行 JSON 编码时出现此异常。我相信 NSDate 与 JSON 编码不兼容。但我必须对日期进行编码。任何解决方案?
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (__NSDate)'
采纳答案by Rushi
FIrst store your data in NSString. And then convert your string to NSDate.
首先将您的数据存储在 NSString 中。然后将您的字符串转换为 NSDate。
You can refer SO:
你可以参考SO:
Converting NSString to NSDate (and back again)
NSString to NSDate conversion problem
回答by pradeepa
Convert NSDate to NSString and try to encode.
将 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;
}
回答by Bhavin
Have you tried ?
你有没有尝试过 ?
updateDate = [NSNumber numberWithFloat:[[NSDate date] timeIntervalSince1970]];
As Described Here : SDK not supporting NSDate objects
如此处所述:SDK 不支持 NSDate 对象
Follow these Steps :
请按照以下步骤操作:
1. Convert the Date in JSON Format :
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. Embed In some array and POST the array.
2.嵌入一些数组并POST数组。
回答by sumizome
As noted, you must first convert your NSDate to an NSString. It's not immediately clear, however, which format the date should be represented in. The answer can be found here: "JSON itself does not specify how dates should be represented, but Javascript does" -- ISO8601.
如前所述,您必须首先将您的 NSDate 转换为 NSString。然而,目前还不清楚日期应该用哪种格式表示。可以在此处找到答案:“JSON 本身没有指定日期的表示方式,但 Javascript 可以”——ISO8601。
Here is an ISO8601 conversion method from a helper category for NSDate, courtesy Erica Sadun:
这是来自 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;
}
If you get an ISO8601 string back in a JSON payload and want to convert it to an NSDate, use this class method for NSDate:
如果您在 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)];
}
回答by Julius
The simplest way to store and retrieve a NSDate object in JSON would be to use the timeIntervalSince1970property of NSDate.
在 JSON 中存储和检索 NSDate 对象的最简单方法是使用NSDate的timeIntervalSince1970属性。
The returned NSTimeInterval (double) is pretty standard and can easily be converted back to a NSDate object using:
返回的 NSTimeInterval (double) 是非常标准的,可以使用以下方法轻松转换回 NSDate 对象:
NSDate dateWithTimeIntervalSince1970:<#(NSTimeInterval)#>
回答by Ismael
You must convert the date to a string before you try to encode it. There are enough examples everywhere so it should be easy to find
在尝试对其进行编码之前,您必须将日期转换为字符串。到处都有足够的例子,所以应该很容易找到
回答by Ted
For our case, we are using Mantleto convert an object to JSON and one of our objects with property NSDate is missing its JSONTransformer
对于我们的案例,我们使用Mantle将对象转换为 JSON,并且我们的一个具有属性 NSDate 的对象缺少其 JSONTransformer
@property (nonatomic) NSDate *expiryDate;
where:
在哪里:
+ (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;
}
回答by Micha? Ziobro
I am doing something like this in my 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)