我正在用 JSON 编写一个 iphone 应用程序,并试图将 JSON 字符串转换为对象(不是字典或数组)。
在 Java 中,多亏了反射,我可以像这样轻松地将 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 );
我想知道这在 objective-c 中是否可行。我目前正在使用 this JSON 框架,但愿意在必要时进行切换。
谢谢,
最佳答案
有一个名为 objectiveresource 的开源项目和 objectivesupport .它们是 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 framework 的分支。你正在使用的。
关于iPhone + JSON + 反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/742521/