That said, I was looking for some in-built library/API to convert my Objective C data model classes into JSON without me providing the mapping (or should I say, remapping) of any sort .
Pretty straightforward requirement, I would think. Partly because of my poor searching skills and partly because of my poor iOS skills, I was kind of surprised to find out that, there are bunch of libraries to convert to and from JSON, however they all needed some sort of mapping to be provided along with the Objective C class to get the job done.
After searching a bit more and looking around, I came across a neat little JSON library that did exactly what I wanted. The library is called JSONModel.
Here is the description from their site
JSONModel automatically introspects your model classes and the structure of your JSON input and reduces drastically the amount of code you have to write.The documentation of JSONModel is quite comprehensive and pretty self explanatory, the intent of this post is to keep reminding myself and other fellow developers of using it every time the need arises to convert Objective C classes to JSON.
Ok so enough chatter. Let's get to business and see an example.
How Do They Do It?
If you are using Cocoa Pods in your project then installation is as simple as adding the following line to the Podfile.
If you are not using Cocoa Pods in your project then, start using it :)
- Let's say we have a Student Objective C class that needs to be converted to and from JSON representation.
- All that needs to be done is, extending it from JSONModel class
- JSONModel is really where the magic happens.
- It adds methods like toJSONString and initWithString to convert Objective C class to and from JSON.
- We need to only declare the properties in the Student class that will be serialized to JSON.
- The sample code to convert Object C data model to and from JSON would look as follows.
That's all folks! Hopefully by the next time when we meet, I would be a better iOS developer than what I am today :).