ioscore-datansdateformatternsjsonserializationgithub-mantle

NSDate issue with NSJSONSerialization when using Mantle library


I have an issue serialising core data managed object into JSON object. I am using Mantle to do this and this is related NSDate. I am getting this error.

'Invalid type in JSON write (__NSDate)'

This is where this exception is throwing. It is fine until code line 4 (NSDictionary *jDict ....)

        //NSManagedObject from Core Data
        Memo *newMemo = [self fetchMemo:memo.uuid];

        NSError *errorMantle;

        //MTLModel model
        BSMemo *memooo = [MTLManagedObjectAdapter modelOfClass:[BSMemo class] fromManagedObject:newMemo error:&errorMantle];

        NSDictionary *jDict = [MTLJSONAdapter JSONDictionaryFromModel:memooo];

        //Serialising using NSJSONSerialization
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jDict options:NSJSONWritingPrettyPrinted error:&error];

This is how I am formatting the NSDate in MTLModel

+ (NSValueTransformer *)dateJSONTransformer {
    static dispatch_once_t onceToken;
    static NSDateFormatter *dateFormatter;

    dispatch_once(&onceToken, ^{
        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"YYYY-MM-dd'T'HH:mm:ssZZZ"];

    });

    return [MTLValueTransformer transformerWithBlock:^id(NSString *string) {
        return [dateFormatter dateFromString:string];
    }];
}

+ (NSValueTransformer *)createdJSONTransformer {
    return [self dateJSONTransformer];
}

JSON parsing fine and this is only happen when try to genarate JSON string from core data. I have tried with different date format. But no luck. Could you please help me how to overcome this?

Updated block

+ (NSValueTransformer *)dateJSONTransformer {
    __block dispatch_once_t onceToken;
    __block NSDateFormatter *dateFormatter;

    dispatch_once(&onceToken, ^{

        dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"YYYY-MM-dd'T'HH:mm:ssZZZ"];
    });

    return [MTLValueTransformer transformerWithBlock:^id(NSString *string) {
        return [dateFormatter dateFromString:string];
    }];
}

I am downloading some data from Rest JSON API and save into core data. Because my app has to be work offline. When try to push data back to the server, I need to convert core data in to JSON and attached with HTTP POST. So I am using Mantle to simplify this process.


Solution

  • Try like this

    + (NSDate*)dateJSONTransformer:(NSString*)dateString {
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
            [dateFormatter setDateFormat:@"YYYY-MM-dd'T'HH:mm:ssZZZ"];
            return [dateFormatter dateFromString:dateString];
    }