Monday, January 27, 2014

How To Convert Objective C data modles into JSON

Recently, I have been trying my hands at iOS and so far its going good.  I must say, I am still learning things.  Before going further this is a disclaimer from my side, I am by no means an expert on iOS and related technologies, so please consider the views mentioned in this post as strictly my own immature views only.

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 :)

Basic Usage
  • 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.
The Student.h file looks like: The Student.m file looks pretty simple The code to convert Student instance to JSON is as follows. The above code has an output that looks like The code to convert JSON string to Student instance is as follows. As you can see we didn't write any extra mapping code to convert Object C data model into JSON. This post is just scratching the surface, JSONModel has got a lot of great features that make this library fun to use.

That's all folks! Hopefully by the next time when we meet, I would be a better iOS developer than what I am today :).
Have some Fun!