RestKit 中的嵌套对象映射
我有以下结构:
获取手册:
//请求
{
"type": "handbook",
"hash": ""
}
//响应
{
"body": {
"songs": [
{
"id": 1,
"length": 1231,
"name": "song 1"
},
{
"id": 2,
"length": 3155,
"name": "song 2"
}
],
"setlists": [
{
"id": 1,
"name": "setlist1",
"songs": [
{
"id": 1
},
{
"id": 2
}
]
},
{
"id": 2,
"name": "set list 2",
"songs": [
{
"id": 3
},
{
"id": 4
},
{
"id": 5
}
]
}
]
},
"state": true,
"type": "handbook"
}
我需要解决两个问题的建议: 1)如何在响应的“正文”中映射对象? 2) 我如何将 Setlist 连接到它的歌曲?
I have following structure:
Get Handbook:
//request
{
"type": "handbook",
"hash": ""
}
//response
{
"body": {
"songs": [
{
"id": 1,
"length": 1231,
"name": "song 1"
},
{
"id": 2,
"length": 3155,
"name": "song 2"
}
],
"setlists": [
{
"id": 1,
"name": "setlist1",
"songs": [
{
"id": 1
},
{
"id": 2
}
]
},
{
"id": 2,
"name": "set list 2",
"songs": [
{
"id": 3
},
{
"id": 4
},
{
"id": 5
}
]
}
]
},
"state": true,
"type": "handbook"
}
I need an advice for solving two problems:
1) How can i map objects in the "body" of response?
2) How can i connect Setlist to it's Songs?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 JSON 解析器(例如 SBJSON)将响应解析为 NSDictionary 和 NSArray 对象的层次结构。要将集合列表中列出的歌曲“连接”到歌曲本身,您必须对这些解析的对象进行一些手动操作。为此,您有几个选项:
您可以添加对歌曲数组中歌曲对象的引用,作为每个设置列表字典中的另一个值。这可以工作,但您必须小心避免保留循环,其中字典保留对直接或间接保留对字典本身的引用的对象的引用。我认为这不一定会对您的数据造成问题,但如果结构不断发展并变得更加复杂,那么处理起来会很麻烦。
您可以定义自己的对象类,而不是直接使用 NSArray 和 NSDictionary。可能具有类似的保留周期复杂性,但比使用集合类更易于管理。
使用适当的 CoreData 建模将数据从这些对象复制到 NSManagedObject 实例中。这是最优雅和最强大的解决方案,但对于您的要求来说可能有点过分了
Use a JSON parser such as SBJSON to parse the response into a hierarchy of NSDictionary and NSArray objects. To "connect" the songs listed in a set list to the songs themselves, you will have to do some manual manipulation of those parsed objects. You have a few options for this:
You could add a reference to the song object within the songs array as another value within each set list dictionary. This can work, but you will have to be careful to avoid retain cycles, where a dictionary retains a reference to a an object that directly or indirectly retains a reference to the dictionary itself. I don't think this would necessarily a problem for your data, but it's a nasty thing to deal with if the structure evolves and gets more complicated.
You could define object classes of your own rather than using NSArray and NSDictionary directly. Could have similar retain cycle complexities, but a little more manageable than doing it with the collection classes.
Copy the data from these objects into NSManagedObject instances with appropriate CoreData modeling. This is the most elegant and robust solution, but may be overkill for your requirements