so I am happily slamming data into my system using JSON and setValuesForKeysWithDictionary until I run into an object that has an NSDate property.
The JSON contains dates with the following format:
BackOrderDate: "2011-03-15T00:00:00"
This gives me an error:
'NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "BackOrderDate"; desired type = NSDate; given type = __NSCFString; value = 2011-03-15T00:00:00
I am using JSON.NET with MVC and the following settings with it:
JsonSerializerSettings serializerSettings = new JsonSerializerSettings();
serializerSettings.Converters.Add(new Newtonsoft.Json.Converters.IsoDateTimeConverter());
string json = JsonConvert.SerializeObject(objects, Formatting.None, serializerSettings);
return Content(json);
Any ideas on how to deal with this issue? I do not want to lose the use of setValuesForKeysWithDictionary since it so fricking fast.
I assume you’re using Core Data (since Core Data produces the error you posted) and that your entity has a property named “BackOrderDate” of type “Date”.
The problem is that JSON doesn’t have a “Date” data type. In your .NET code you’ve handled this by telling the JSON serialize to convert dates to IS-formatted strings.
You need to perform the opposite conversion when you parse the JSON data in your iOS app, before you pass the data to
setValuesForKeysWithDictionary:.You can parse a string into an
NSDateusing anNSDateFormatter, and you can easily find lots of examples of that on the web.How you perform the parsing before calling
setValuesForKeysWithDictionary:depends on what you’re using the parse the JSON.If you’re using Apple’s
NSJSONSerialization, you should probably use theNSJSONReadingMutableContainersoption. Then go into the dictionary and replace the date string with anNSDateobject before callingsetValuesForKeysWithDictionary:.If you’re using some other JSON parser (like SBJSON), I don’t know the best way to do the replacement.