【发布时间】:2017-03-11 11:21:11
【问题描述】:
我正在使用 RestKit 在我的 iOS 项目中映射 JSON 对象。 到目前为止一切正常,但我在映射自定义类型的子数组时遇到了问题。
JSON 如下所示:
{ "Result" : "OK", "Total": "1","content": [
{"article":
{
"title": "sample_title",
"author": "sample_author",
"article_details": [
{"text":
{
"body": "sample_body",
}
},
{"image":
{
"image": "sample_image"
}
},
{"quote":
{
"quote": "sample_quote",
}
}
{"text":
{
"body": "sample_body",
}
},
]}
}]
}
请注意,article_detail 对象类型可以以任意数量或顺序出现。 此外,重要的是要注意我需要存储这些对象出现的顺序,以及它的每个类型。
为此,为了简化数据操作,我使用 CoreData 自动生成了两个 NSManagedObjects。如下:
extension Article {
public var title: String?
public var author: String?
public var details: NSOrderedSet?
}
extension ArticleDetail {
public var body: String?
public var image: String?
public var quote: String?
}
我的映射如下:
//Detail mapping
let detailsMapping = RKEntityMapping(forEntityForName: "ArticleDetail", in: objectManager.managedObjectStore)
detailsMapping?.addAttributeMappings(from: [
"image" : "image",
"body" : "body",
"quote" : "quote",
]
)
//Article mapping
let articleMapping = RKEntityMapping(forEntityForName: "Article", in: objectManager.managedObjectStore)
articleMapping?.addAttributeMappings(from: [
"title" : "title",
"author" : "author",
]
)
//Relation mapping
articleMapping!.addPropertyMapping(RKRelationshipMapping(fromKeyPath: "article_details.text", toKeyPath: "details", with: detailsMapping))
//Response descriptior
let articleResponseDescriptor = RKResponseDescriptor(
mapping: articleMapping,
method: RKRequestMethod.GET,
pathPattern: nil,
keyPath: "content.article",
statusCodes: IndexSet(integer: 200)
)
objectManager.addResponseDescriptor(articleResponseDescriptor)
这适用于文章信息。然而,正如预期的那样,由于
fromKeyPath: "article_details.text"
它只映射“文本”对象。
识别类型很容易,检查文章详细对象中哪些参数为nil。
类似的问题可以在 RestKit - Map keypath of an array to the object inside of that array
我怎样才能在 Swift 中使用 RestKit 来完成这项工作?
非常感谢。
-N
【问题讨论】:
标签: ios json swift core-data restkit