6

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;
}
1
  • age does not have asterisk symbol because it's an integer Aug 25, 2011 at 16:04

3 Answers 3

5

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

1
  • Awesome. Thanks paull. I didn't know that NSObject's supported this sort of protocol. I can write my own simple mapper now.
    – pschang
    Apr 13, 2010 at 22:49
4

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

https://github.com/dchohfi/KeyValueObjectMapping

1
  • Could this be used to convert json to NSObjects? Apr 19, 2013 at 9:07
1

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.