在 NSDictionary 中传递 NSDate 并转换为 NSData 以进行 jsondata 修复

Pass NSDate in NSDictionary and convert into NSData for jsondata fix

我有一个 json 有 NSStringNSDate 数据 (dob) 我创建了它的 NSDictionary,但是当我使用代码

将它转换为数据时
 NSData *requestData1 = [NSJSONSerialization dataWithJSONObject:json_inputDic options:0 error:&error];

它通过报错杀死

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

我的问题是我需要通过 dob,因为 NSDate 是强制性的。我该如何解决?

例如

   NSDate *newDate = [NSDate date];
    [dic setValue:newDate forKey:@"dob"];


    NSString *good = @"good";

    [dic setValue:good forKey:@"good"];

    NSLog(@"dic=%@",dic);
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error]; //it gives error

    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"jsonData as string:\n%@", jsonString);

NSDate 无法在 JSON 中本地表示。正如 NSJSONSerialization 文档所说:

An object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.

  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.

  • All dictionary keys are instances of NSString.

  • Numbers are not NaN or infinity.

根据您的问题,日期在您的 JSON 中应该以何种格式表示不清楚。通常,您以某种标准日期字符串格式(例如 ISO 8601/RFC 3339 格式,如 2016-01-25T06:54:00Z)格式化日期。

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZZZZZ";

或者,对于 macOS 10.12 和 iOS10,您可以:

NSISO8601DateFormatter *formatter = [[NSISO8601DateFormatter alloc] init];

然后:

NSString *birthDateString = [formatter stringFromDate:birthDate];

有关详细信息,请参阅 Apple Technical Q&A 1480

或者,也许因为今天是生日,您只需要 yyyy-MM-dd

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
formatter.dateFormat = @"yyyy-MM-dd";
NSString *birthDateString = [formatter stringFromDate:birthDate];

最重要的是,您必须告诉我们您的 Web 服务希望日期的格式是什么格式,然后我们可以帮助您相应地设置格式。