使用RestKit我在映射以下JSON时遇到问题: 如您所见,languages属性/关系不包含语言实体的任何关键信息。
{
"data": {
"version": "1.0",
"languages": {
"en": "English",
"es": "Espanol"
}
}
}
json - "数据" object被映射到RootData对象,该对象适用于version属性。
class RootData: NSManagedObject {
@NSManaged var version: String?
@NSManaged var languages: NSOrderedSet?
}
现在,我想映射关键路径" data.languages"一个OrderedSet语言对象,如:
class Language: NSManagedObject {
@NSManaged var identifier: String?
@NSManaged var name: String?
}
我想最终得到一组语言对象:
(pseudo-code)
rootData.firstLanguage.identifier == "en"
rootData.firstLanguage.name == "English"
rootData.secondLanguage.identifier == "es"
rootData.secondLanguage.name == "Espanol"
但我不知道如何映射RootData->语言1:n关系。
谢谢,任何帮助表示赞赏。
答案 0 :(得分:0)
像往常一样为嵌套内容创建映射,然后在其上设置forceCollectionMapping
,让RestKit将字典转换为数组,以便映射处理。
答案 1 :(得分:0)
此映射解决了它:
let rootMap = RKEntityMapping(forEntityForName: "RootData", inManagedObjectStore: store)
let rootDict = ["data.version": "version",] as [NSObject: AnyObject]!
rootMap.addAttributeMappingsFromDictionary(rootDict)
let languagesMap = RKEntityMapping(forEntityForName: "Language", inManagedObjectStore: store)
languagesMap.forceCollectionMapping = true // thanks @Wain
//
// the following solved my problem regarding the mapping:
// - Key not present: * map from representation
// * reference identifier in name-mapping
// - Add identification attribute to keep them unique
//
let languageDict = ["(identifier)": "name",] as [NSObject : AnyObject]!
languagesMap.addAttributeMappingsFromDictionary(languageDict)
languagesMap.identificationAttributes = ["identifier"]
languagesMap.addAttributeMappingFromKeyOfRepresentationToAttribute("identifier")
rootMap.addPropertyMapping(
RKRelationshipMapping(
fromKeyPath: "data.languages",
toKeyPath: "languages",
withMapping: languagesMap)
)
感谢任何人如何加入。