我正在使用 Grails Webflow,无论我传递给 View 什么对象,它都必须被序列化。 我的域模型“实现可序列化”,因此它们可以工作。
问题是当我从 WebService 收到响应时。 它属于 org.json.JSONArray 类。
我只想将整个数组传递给 View ,但它没有实现可序列化, 所以失败了,
关于我如何通过这个,或者我的最佳选择有什么想法吗?
我可以只编辑 org.json 库的源代码并使每个类都“imp 可序列化”吗?
或者将结果处理为“imp Serialized”的域对象
最佳答案
将其作为一个transient
属性包装在一个实现Serialized
的类中,并具有readObject()
和writeObject()
被覆盖。
public class SerializableJSONArray implements Serializable {
private transient JSONArray jsonArray;
public SerializableJSONArray(JSONArray jsonArray) {
this.jsonArray = jsonArray;
}
public JSONArray getJSONArray() {
return jsonArray;
}
private void writeObject(ObjectOutputStream oos) throws IOException {
oos.defaultWriteObject();
oos.writeObject(jsonArray.toString());
}
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException, JSONException {
ois.defaultReadObject();
jsonArray = new JSONArray((String) ois.readObject());
}
}
您会看到有一个 getter 返回包装的 JSONArray。相反,请在您的域对象中使用它。您还可以选择让此类扩展 JSONArray
并将其所有方法委托(delegate)给包装的 JSONArray。一个像样的 IDE 可以在一秒钟内自动生成它们。
关于java - "org.json.JSONArray implements Serializable": What's the best option to achieve this?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2035283/