Java JSON序列化 - 最佳实践 [英] Java JSON serialization - best practice
问题描述
我需要为某些对象实现JSON序列化,而在与通用集合集成时遇到问题。
所有可序列化的类实现此接口(JSONObject来自 this < a> library):
接口JSONSerializable {
public JSONObject dump()throws JSONException // serializes object
public void load(JSONObject obj)throws JSONException //反序列化对象
}
代码我基于java.util.list的集合看起来或多或少是这样的:
class AwesomeList< T extends JSONSerializable>实现JSONSerializable {
private LinkedList< T> items = new LinkedList< T>();
...
...
public JSONObject dump()throws JSONException {
JSONObject result = new JSONObject();
JSONArray a = new JSONArray(); (t i:items)
{
a.put(i.dump());
}
result.put(items,a);
返回结果;
}
public void load(JSONObject obj)throws JSONException {
//这里是我的问题
}
}
$我的问题是:当我从JSONObject加载AwesomeList时,我需要创建它的元素,但这是不可能的,因为java禁止我写 p>
T newItem = new T();
newItem.load(obj);
如何修改我对此任务的方法?
解决方案你是否绑在这个图书馆? Google Gson 非常受欢迎。我自己没有使用泛型,但是他们的首页说,Gson认为对泛型的支持非常重要。
I need to implement JSON serialization for some objects, and I've encountered a problem when it came to integration with generic collections.
All serializable classes implement this interface (JSONObject comes from this library):
interface JSONSerializable{
public JSONObject dump() throws JSONException //serializes object
public void load(JSONObject obj) throws JSONException //deserializes object
}
Code for my collection based on java.util.list looks more or less like this:
class AwesomeList<T extends JSONSerializable> implements JSONSerializable{
private LinkedList<T> items = new LinkedList<T>();
...
...
public JSONObject dump() throws JSONException {
JSONObject result = new JSONObject();
JSONArray a = new JSONArray();
for(T i : items){
a.put(i.dump());
}
result.put("items", a);
return result;
}
public void load(JSONObject obj) throws JSONException{
//here is my problem
}
}
My problem is: When I load AwesomeList from JSONObject, I need to create its elements but it's impossible since java forbids me to write
T newItem = new T();
newItem.load(obj);
How should I modify my approach to this task?
解决方案 Are you tied to this library? Google Gson is very popular. I have myself not used it with Generics but their front page says Gson considers support for Generics very important.
这篇关于Java JSON序列化 - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!