Pass NSDate to NSDictionary and convert to NSData for jsondata fix

I have json with data NSStringand NSDate(dob) I create it NSDictionary, but when I convert it to data using code

 NSData *requestData1 = [NSJSONSerialization dataWithJSONObject:json_inputDic options:0 error:&error];

He kills, giving an error

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

My problem is that I need to pass dob, since NSDate is required. How to fix it?

for example

   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);
+4
source share
1 answer

NSDatecannot be represented in JSON natively. As the documentation says NSJSONSerialization:

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

  • The top level object is NSArrayor NSDictionary.

  • NSString, NSNumber, NSArray, NSDictionary NSNull.

  • NSString.

  • NaN .

, , ​​ 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 iOS 10 :

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];

, , - , .

+6

Source: https://habr.com/ru/post/1625850/


All Articles