Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass NSDate in NSDictionary and convert into NSData for jsondata fix

I have a json having NSString and NSDate data (dob) I create an NSDictionary of it, but when I am converting it into data using code

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

It kills by giving error

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

My problem is that i need to pass dob as NSDate is mandatory. How do I 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);
like image 266
9to5ios Avatar asked Feb 07 '23 22:02

9to5ios


1 Answers

NSDate cannot be represented in JSON natively. As NSJSONSerialization documentation says:

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.

It's unclear from your question in what format the date should be represented in your JSON. Often, you format dates in some standard date string format (e.g. ISO 8601/RFC 3339 format like 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";

Or, for macOS 10.12 and iOS 10, you can do:

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

Then:

NSString *birthDateString = [formatter stringFromDate:birthDate];

See Apple Technical Q&A 1480 for more information.

Or perhaps, because it's a birthday, you only need 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];

Bottom line, you have to tell us what format your web service is expecting the dates to be formatted, and then we can help you format it accordingly.

like image 79
Rob Avatar answered Feb 10 '23 12:02

Rob