Java JSON 序列化 - 最佳实践

发布于 2024-12-06 13:43:54 字数 1110 浏览 1 评论 0原文

我需要为某些对象实现 JSON 序列化,并且在与通用集合集成时遇到了问题。

所有可序列化的类都实现此接口(JSONObject 来自 库):

interface JSONSerializable{
    public JSONObject dump() throws JSONException //serializes object
    public void load(JSONObject obj) throws JSONException //deserializes object
}

基于 java.util 的我的集合的代码。列表看起来或多或少像这样:

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
    }
}

我的问题是:当我从 JSONObject 加载 AwesomeList 时,我需要创建它的元素,但这是不可能的,因为 java 禁止我写 我

T newItem = new T();
newItem.load(obj);

应该如何修改完成此任务的方法?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

孤者何惧 2024-12-13 13:43:54

您与这个图书馆有联系吗? Google Gson 非常受欢迎。我自己没有将它与泛型一起使用,但他们的首页说 Gson 认为对泛型的支持非常重要。

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.

原谅我要高飞 2024-12-13 13:43:54

正如其他人所暗示的那样,您应该考虑转储 org.json 的库。如今它已经过时了,试图解决它的问题是浪费时间。

但对于具体问题;类型变量 T 没有任何信息可以帮助您,因为它只不过是编译时信息。
相反,您需要传递实际的类(作为“Class cls”参数),然后可以使用“cls.newInstance()”创建一个实例。

As others have hinted, you should consider dumping org.json's library. It's pretty much obsolete these days, and trying to work around its problems is waste of time.

But to specific question; type variable T just does not have any information to help you, as it is little more than compile-time information.
Instead you need to pass actual class (as 'Class cls' argument), and you can then create an instance with 'cls.newInstance()'.

空城之時有危險 2024-12-13 13:43:54

好吧,当将其写入文件时,您确实知道 T 类是什么,因此您可以将其存储在 dump 中。然后,当读回它时,您可以使用反射动态调用它。

public JSONObject dump() throws JSONException {
    JSONObject result = new JSONObject();
    JSONArray a = new JSONArray();
    for(T i : items){
        a.put(i.dump());
        // inside this i.dump(), store "class-name"
    }
    result.put("items", a);
    return result;
}

public void load(JSONObject obj) throws JSONException {
    JSONArray arrayItems = obj.getJSONArray("items");
    for (int i = 0; i < arrayItems.length(); i++) {
        JSONObject item = arrayItems.getJSONObject(i);
        String className = item.getString("class-name");
        try {
            Class<?> clazzy = Class.forName(className);
            T newItem = (T) clazzy.newInstance();
            newItem.load(obj);
            items.add(newItem);
        } catch (InstantiationException e) {
            // whatever
        } catch (IllegalAccessException e) {
            // whatever
        } catch (ClassNotFoundException e) {
            // whatever
        }
    }

Well, when writing it out to file, you do know what class T is, so you can store that in dump. Then, when reading it back in, you can dynamically call it using reflection.

public JSONObject dump() throws JSONException {
    JSONObject result = new JSONObject();
    JSONArray a = new JSONArray();
    for(T i : items){
        a.put(i.dump());
        // inside this i.dump(), store "class-name"
    }
    result.put("items", a);
    return result;
}

public void load(JSONObject obj) throws JSONException {
    JSONArray arrayItems = obj.getJSONArray("items");
    for (int i = 0; i < arrayItems.length(); i++) {
        JSONObject item = arrayItems.getJSONObject(i);
        String className = item.getString("class-name");
        try {
            Class<?> clazzy = Class.forName(className);
            T newItem = (T) clazzy.newInstance();
            newItem.load(obj);
            items.add(newItem);
        } catch (InstantiationException e) {
            // whatever
        } catch (IllegalAccessException e) {
            // whatever
        } catch (ClassNotFoundException e) {
            // whatever
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文