Can't serialize NSDate with CJJsonSerializer

459 views Asked by At

I try to add NSDate to NSMutableDictionary, and then make it a JSon string with this methods:

NSMutableDictionary *d = [[NSMutableDictionary alloc]init];
[d setObject:[NSDate date] forKey:@"date"];
NSData *jsondata = [[CJSONSerializer serializer] serializeDictionary:d error:nil];
NSString *requestBody = [[[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding] autorelease];

And i have couple of issue: 1) The jsondata is nil, and then the requestBody is nil too. 2) The [NSDate date] getting me wrong date, not like the date in my iPhone:

2013-01-19 11:48:46 +0000

Any help with this issue?

Edit:

When i print the error i got this msg:

Error Domain=TODO_DOMAIN Code=-1 "Cannot serialize data of type '__NSDate'" UserInfo=0x177850 {NSLocalizedDescription=Cannot serialize data of type '__NSDate'}

It's not possible to do it?

2

There are 2 answers

0
Simon On BEST ANSWER

It seems very unlikely that the dictionary would fail to insert the date. It seems much more likely that the problem is with the CJSONSerializer.

Try the following:

NSMutableDictionary *d = [[NSMutableDictionary alloc]init];
[d setObject:[NSDate date] forKey:@"date"];

NSError *error = nil;
NSData *jsondata = [[CJSONSerializer serializer] serializeDictionary:d error:&error];

if (!jsonData)
{
    NSLog(@"Error %@ while serialising to JSON");
}

NSString *requestBody = [[[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding] autorelease];

You should see an error printed to the console.

UPDATE

OK, so it looks like we were right, and CJSONSerializer can't serialise dates. So you need to turn your date into a string. This is done with NSDateFormatter.

NSMutableDictionary *d = [[NSMutableDictionary alloc]init];
NSDate *date = [NSDate date];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss z"];
NSString *dateString = [dateFormatter stringFromDate:date];

[d setObject:dateString forKey:@"date"];

NSError *error = nil;
NSData *jsondata = [[CJSONSerializer serializer] serializeDictionary:d error:&error];

if (!jsonData)
{
    NSLog(@"Error %@ while serialising to JSON");
}

NSString *requestBody = [[[NSString alloc] initWithData:jsondata encoding:NSUTF8StringEncoding] autorelease];

Hopefully you should now get the formatted date in your JSON. You can vary the format by changing the string you pass to stringWithDate:. If you're doing this a lot, you'll want a single date formatter as creating them is costly.

0
Carl Veazey On

JSON doesn't support dates as a standard type, so there is no automatic way to serialize an NSDate. You must either pass a string representation of the date, or a numeric timestamp representation. For instance, you could serialize it as a timestamp by doing something like:

[d setObject:@([[NSDate date] timeIntervalSince1970]) forKey:@"date"]