iPhone + JSON +反射

tba*_*tba 5 iphone reflection cocoa json objective-c

我正在用JSON编写一个iphone应用程序,并试图将JSON字符串转换为对象(NOT Dictionaries或Arrays).

在Java中,感谢Reflection,我可以轻松地将JSON转换为javabean实例,如下所示:

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 );
Run Code Online (Sandbox Code Playgroud)

我想知道这是否可能在objective-c中.我目前正在使用 JSON框架,但如果有必要,我愿意切换.

谢谢,

ker*_*emk 4

有一个名为ObjectiveResourceObjectiveSupport的开源项目。它们是 Ruby 和 RESTful 开发领域中所谓的 ActiveResource 和 ActiveSupport 的部分 Objective-C 实现。Objectivesupport 的部分工作是序列化和反序列化 JSON(以及 XML)对象。如果您不想按原样使用完整的框架,您可以查看 Objectivesupport 的源代码,在那里您将看到它们与 NSObject 之间的序列化实现。下面列出了您要查看的具体代码:(基本上作为 NSObject、NSArray 和 NSDictionary 类型上的类别实现) http://github.com/yfactorial/objectivesupport/tree/d08b5be6c0f7a2b0196b6ec17e4441bb146c4e23/Classes/lib/Serialization/JSON

顺便说一句,他们似乎正在使用与您正在使用的相同JSON 框架的分支。