Nested objects mapping in RestKit
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?
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
精彩评论