I am trying to parse a json string straight into a managed object.
The json string contains all strings, but my Entity has Date objects.
if this is my json string
{
"name":"John",
"dob": "12/12/2008",
etc...
}
and here’s my entity Person:
name : NSString
dob: Date
etc...
I want to parse that json straight through by looping through the keys of the Json dict, and setting the values to the matching keys of my entity:
Person *aPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext];
NSArray *keys = [jsonDict allKeys];
for (NSString *key in keys) {
[aPerson setValue:[jsonDict valueForKey:key] forKey:key];
}
This only works if all my entity’s properties are NSStrings.
How can I get the type/class of my entity’s property to be able to set the various types?
eg.
if key = @”dob”
how can I get the type/class of aPerson.dob?
so my code will look something like:
Person *aPerson = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:managedObjectContext];
NSArray *keys = [jsonDict allKeys];
for (NSString *key in keys) {
if([[aPerson objectForKey:key] isKindOfClass:[NSDate class]])
{
// Create an NSDate object
}else{
[aPerson setValue:[jsonDict valueForKey:key] forKey:key];
}
}
thanks
UPDATE:
Ok I tried using the isKindOfClass and here’s the result was:
// for key = @"name"
// aPerson.name is NSString
[[aPerson valueForKey:key] isKindOfClass:[NSString class]] => TRUE
[[aPerson valueForKey:key] isKindOfClass:[NSObject class]] => TRUE
// for key = @"age"
// aPerson.age is NSNumber
[[aPerson valueForKey:key] isKindOfClass:[NSNumber class]] => TRUE
[[aPerson valueForKey:key] isKindOfClass:[NSObject class]] => TRUE
// for key = @"dob"
// aPerson.dob is NSDate
[[aPerson valueForKey:key] isKindOfClass:[NSDate class]] => FALSE
[[aPerson valueForKey:key] isKindOfClass:[NSObject class]] => FALSE
how is that?
@dynamic dob and NSDate, is notOfClass NSDate!
please tell me what I am missing!
Thanks a lot to Rog, for sending me in the right direction, I ended up overriding my setter as below:
and all works great now, instead of a 1000 lines of code parsing, it’s all done in 3!
nice one!