2

I am using the json google library. we can have this:

Public Class JsonParsing<T> {   

     private Gson gson;

     public JsonParsing(GsonBuilder builder) {
         this.gson = builder.create();
     }

     public T[] fromJsonFromArray(String json, Class<T[]> classOfT) {
         return gson.fromJson(json, classOfT);
     }
}

How we can create the instance of Class<T[]> in order to pass to this method?

Addenda:

I tried to create a generic method :

    public <T> T[] fromJsonFromArray(String json) {
        final Type type = new TypeToken<T[]>(){}.getType();
        return gson.fromJson(json, classOfT);
    }

It seems that I can not have a T[] as return. Then how can I parse an array of data with json format? Note: It is possible to do it in a non-generic way. Couldn't we have any generic solution?

4

2 回答 2

2

您可以将方法更改为:

public T fromJsonFromArray(String json, Class<T> classOfT) {
    return gson.fromJson(json, classOfT);
}

并将其称为(例如):

fromJsonFromArray(someString, new Byte[0].getClass());

注意:令我震惊的是,这可能应该是这样的通用方法:

public <T> T fromJsonFromArray(String json, Class<T> classOfT) {
    return gson.fromJson(json, classOfT);
}

如果您依赖封闭类型中的类型参数(您的第一个示例就是这样做的),我看不出接受classOfT参数的目的。

于 2013-06-28T08:55:36.523 回答
2

尝试使用TokenType

就像是?

Type yourType = new TypeToken<YourClass[]>() {}.getType();
于 2013-06-28T09:00:03.673 回答