views:

2401

answers:

3

Hi,

I'm writing an iphone application with JSON and am trying to turn JSON strings into objects (NOT Dictionaries or Arrays).

In Java, thanks to Reflection, I can easily turn JSON into javabean instances like this:

import net.sf.json.JSONObject;
class MyBean {
    private String property;
    public String getProperty() { return property; }
    public void setProperty(String property) { this.property=property; }
}

// turn JSON string into a MyBean instance
String str = "{\"property\":\"some value\"}";  
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON( str );
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setRootClass( MyBean.class );
MyBean instance = (MyBean) JSONSerializer.toJava( jsonObject, jsonConfig );

I was wondering if this was possible in objective-c. I am currently using this JSON framework but am willing to switch if necessary.

Thanks,

A: 

Maybe looking at the Objective-C Runtime Reference could help you !

There are some functions (like class_createInstance and object_setInstanceVariable) that could help you.

Rémy BOURGOIN
That would work, but I was hoping someone else had already done that and implemented it into a JSON parsing library :)
brainfsck
If you want to do that, without re-creating an whole JSON parser, you could transform JSON to NSDictionary with the existing framework, loop on it, and call the runtime functions. It is not an optimized method, but it could work ;)
Rémy BOURGOIN
+4  A: 

There is an open source project called objectiveresource and objectivesupport. They are partial Objective-C implementations of a what is called ActiveResource and ActiveSupport in the Ruby and RESTful development world. Part of what objectivesupport does is serializing and deserializing JSON (as well as XML) object. If you don't want to use the full frameworks as is, you can take a look at the source code for objectivesupport and there you will see their implementation of serializing to/from an NSObject. The specific code you want to look at are listed below: (Basically implemented as a category on the NSObject, NSArray and NSDictionary types) http://github.com/yfactorial/objectivesupport/tree/d08b5be6c0f7a2b0196b6ec17e4441bb146c4e23/Classes/lib/Serialization/JSON

BTW, they seem to be using a fork of the same JSON framework that you are using.

keremk
I ended up copying the whole project because it was too difficult to extract only the parts that did JSON->object (de)serialization. But it worked, thanks
brainfsck
A: 

Just in case anyone else gets here when looking for an answer to this question, there's another project that has exactly what you're looking for: JSON for iPhone, and nothing else.

Here: http://code.google.com/p/json-framework/

Adam Lang