I\'m parsing some JSON which comes to me in this format:
{
dataId = \"823o7tr23d387g\";
category = \"link\";
details = {
text = \"Some text associated wi
Check out this article about using MagicalRecord to automatically import JSON, specifically the data keypath support section
http://www.cimgf.com/2012/05/29/importing-data-made-easy/
Data Keypath Support
Key Value Coding is a common and effective tool in Objective C. MagicalImport gives you access to some of this power by allowing you to specify keyPaths as part of a mappedKeyName. If you’re familiar with KVC, this should be a fairly straightforward feature as Magicalmport passed these specified keys to the KVC methods under the covers. Keypath support allows you to map data to an entity that may not have exactly the same hierarchy as the data model. For example, a data entity may store latitude and longitude, but the source data looks more like this:
{ "name": "Point Of Origin", "location": { "latitude": 0.00, "longitude": 0.00 } }
In this case, we can specify as our data import key paths, location.latitude and location.longitude in our mappedKeyName configuration to dig into the nested data structure and import those values specifically into our core data entity.
The blog Scott mentioned is a must read for who use MagicalRecord.
In addition, if the default + (id) importFromObject:(id)data
doesn't work on some of your NSDictionary data, you can always override the - (BOOL) importValuesForKeysWithObject:(id)objectData
method in your NSManagedObject subclass to achieve the exact control over mapping.
Here's a snippet from one of my recent project:
// override MagicalRecord's implementation with additional set up for Dialogue relationship
- (BOOL) importValuesForKeysWithObject:(id)objectData {
BOOL result = [super importValuesForKeysWithObject:objectData];
// update lesson-dialogue data
id dialogueDicts = [objectData objectForKey:@"dialogue"];
if ([dialogueDicts isKindOfClass:[NSArray class]]) {
for (id dialogueDict in dialogueDicts) {
DialogueSentence *dialogue = [DialogueSentence findFirstByAttribute:@"id" withValue:[[dialogueDict objectForKey:@"id"]];
if (dialogue == nil) {
dialogue = [DialogueSentence createEntity];
}
[dialogue importValuesForKeysWithObject:dialogueDict];
[self addDialoguesObject:dialogue]; // connect the relationship
}
}
return result;
}
By the way, you may want to create a category of your NSManagedObject subclass and write the overriding code there, because when you upgrade your Core Data model version and re-generate the NSManagedObject subclasses, your own code won't be wiped out.