Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone + JSON + Reflection

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,

like image 495
tba Avatar asked Oct 14 '22 16:10

tba


1 Answers

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.

like image 80
keremk Avatar answered Oct 23 '22 10:10

keremk