Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object mapping in objective-c (iphone) from JSON

For my iPhone app, I'm consuming a RESTful service and getting JSON. I've found libraries to deserialize this into an NSDictionary. However, I'm wondering if there are any libraries to deserialize the JSON/NSDictionary/Property List into my object (an arbitrary one on my side).

The java equivalent would be the object-relational mappers although the sort of object mapping I'm looking for is relatively straightforward (simple data types, no complex relationships, etc.).

I noticed that Objective-C does have introspection so it seems theoretically possible but I haven't found a library to do it.

Or is there a simple way to load an object from an NSDictionary/Property List object that doesn't require modification every time the object changes?

For example:

{ "id" : "user1",
  "name" : "mister foobar"
  "age" : 20 }

gets loaded into object

@interface User : NSObject {
 NSString *id;
 NSString *name;
 int *age;
}
like image 841
pschang Avatar asked Apr 13 '10 03:04

pschang


3 Answers

Take a look at the NSKeyValueCoding protocol. In particular, the methods setValuesForKeysWithDictionary: and dictionaryWithValuesForKeys:

like image 191
Paul Lynch Avatar answered Oct 25 '22 10:10

Paul Lynch


I've made a framework to do this automatically. Check out.

https://github.com/dchohfi/KeyValueObjectMapping

like image 27
dchohfi Avatar answered Oct 25 '22 10:10

dchohfi


Take a look at the Loid project on Sourceforge. My intent is to provide what you are talking about.

Right now the framework can reverse engineer a Meta description about an Object (such as your "User" object) and can serialize to and from a LoidTypeData object. My intent is to create a LoidTypeData instance from an incoming JSON block and then bind it to the Object. Of course, the reverse will also be there.

It is open source and GPL. You will need to access the code from SVN at the moment, don't quite know how to build distro for Mac.

-- Frank

like image 28
Frank C. Avatar answered Oct 25 '22 10:10

Frank C.