Java JSON 序列化 - 最佳实践 [英] Java JSON serialization - best practice

查看:21
本文介绍了Java JSON 序列化 - 最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to implement JSON serialization for some objects, and I've encountered a problem when it came to integration with generic collections.

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

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
}

我的基于 java.util.list 的集合的代码看起来或多或少是这样的:

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

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

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?

推荐答案

您是否与此库相关联?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.

这篇关于Java JSON 序列化 - 最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆