我正在解析一些JSON,这些JSON的格式如下:
{
dataId = "823o7tr23d387g";
category = "link";
details = {
text = "Some text associated with the link";
url = "http://www.url.com";
thumbnail_url = "http://www.url.com/picture.jpeg";
};
source = "CNN";
},
{
...
},MagicalRecord有一个很好的导入方法:+ (id) importFromObject:(id)data;,但是它是否支持JSON字典中的字典,以便它可以自动将details {}映射到适当的属性?
是否有命名约定或我需要使用的东西?
发布于 2012-08-21 22:52:22
查看这篇关于使用MagicalRecord自动导入JSON的文章,特别是数据密钥路径支持部分
http://www.cimgf.com/2012/05/29/importing-data-made-easy/
数据密钥路径支持
在Objective C中,键值编码是一个常见且有效的工具。MagicalImport允许您将keyPaths指定为mappedKeyName的一部分,从而使您能够使用其中的一些功能。如果您熟悉KVC,这应该是一个相当简单的功能,因为Magicalmport在幕后将这些指定的键传递给了KVC方法。Keypath支持允许您将数据映射到可能与数据模型具有不完全相同的层次结构的实体。例如,数据实体可能存储纬度和经度,但源数据看起来更像这样:
{ "name":“原点”,"location":{“纬度”:0.00,“经度”:0.00 }}
在本例中,我们可以指定mappedKeyName配置中的location.latitude和location.longitude作为数据导入键路径,以深入研究嵌套数据结构,并将这些值专门导入到核心数据实体中。
发布于 2012-08-21 23:11:42
斯科特提到的博客是使用MagicalRecord的人的必读之处。
此外,如果默认的+ (id) importFromObject:(id)data在某些NSDictionary数据上不起作用,您始终可以覆盖NSManagedObject子类中的- (BOOL) importValuesForKeysWithObject:(id)objectData方法,以实现对映射的精确控制。
这是我最近的一个项目中的一个片段:
// 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;
}顺便说一句,您可能希望创建NSManagedObject子类的一个类别并在其中编写覆盖代码,因为当您升级核心数据模型版本并重新生成NSManagedObject子类时,您自己的代码不会被清除。
https://stackoverflow.com/questions/12057495
复制相似问题