使用没有属性名称的 RestKit 映射 JSON

Mapping JSON with RestKit without attribute names

使用 RestKit 我在映射以下内容时遇到问题 JSON: 如您所见,语言attribute/relationship不包含任何语言实体的关键信息。

{
  "data": {
    "version": "1.0", 
    "languages": {
      "en": "English",
      "es": "Espanol"
    }
  }
}

json-"data" 对象映射到 RootData 对象,适用于 属性.

版本
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->Languages 1:n 关系。

谢谢,如有任何帮助,我们将不胜感激。

像往常一样为嵌套内容创建映射,然后在其上设置 forceCollectionMapping 让 RestKit 将字典转换为数组以供映射处理。

这个映射解决了它:

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)
    )

感谢任何人的参与。