Tuesday, January 1, 2013

iOS -- JSON to Core Data

Now, using JSON to pass data from web service to iOS app is quite popular. JSON is much light weight than XML or others.  But how can we mapping JSON data to Core data class or object ?

Here is the answer:,

At first, you have get your json data from web service or wcf. Here is the format of the JSON,

For example:


{"BOSS":[{"name":"John Carlos","mobile":"12345678","email":"a@b.com"},{"name":"Steve Jobs","mobile":"87654321","email":"d@e.com"}]}

 The class name is BOSS, and it has three attributes, whihc is name, mobile and email.


Second, you must have a json library to parse the json string, I am using SBJSON framework.

And the you parse the json string into a NSDictionary. Like below

      
Thirdly, mapping the json data to your Core data object using setValuesForKeysWithDictionary method


In the core data you created, the Boss entity's attribute must same as the JSON data attribute,
like name, mobile and email.

In this way, you can quickly insert you json data to your core data.

And more, here is a very useful link about JSON to core data, you can have a look:

http://www.cimgf.com/2011/06/02/saving-json-to-core-data/