I have a core data object graph (consisting of two entities linked by a to-many relationship).
I was curious, as a relatively inexperienced iPhone developer, whether anyone could recommend an approach, and a suitable JSON implementation for the iPhone, which would allow me to:
-
convert the core data records into a JSON string (whilst maintaining the relationship between the entities); and
-
convert the JSON string back into core data objects (again preserving the relationship between entities).
I have searched, unsuccessfully, for a tutorial/code sample on this point so any assistance would be gratefully received.
Best Answer
First, pick a JSON library to use, I personally like TouchJSON but several others out there are quite nice as well. The complicated part, although not very hard, is to convert your managed objects into suitable structures for the conversion. I wrote this real quick so it may have an error or two :)
The methods you call are:
And the implementation is as follows:
Now this is recursive so you can easily end up translating your entire persistent store if you are not careful. Watch your relationships and make sure that they only go "down" the object tree so that you only get the objects you want translated.