Gson和通用不起作用

时间:2015-07-19 12:53:29

标签: java json gson

我有一个班级

public class ContactsData<T> {

    @SerializedName(value = "data")
    public ArrayList<T> data;

    public ContactsData<T> fromJson(String json) {
        return BBAPI.getGson().fromJson(json, new TypeToken<ContactsData<T>>() {
        }.getType());
    }

}

然后我尝试使用函数fromJson从json反序列化类我得到了Object ContactsData但是在数组数据中没有类型为T的对象,但是LinkedTreeMap

如何做到正确?

我想在类而不是子类上使用,因为我有来自服务器的响应,具有一种格式

{"data":[array of different types]}

2 个答案:

答案 0 :(得分:0)

您必须为每种T类型注册自定义类型适配器。

例如:

Gson gson = new GsonBuilder().registerTypeAdapter(MyCustomClass.class, new MyCustomClassInstanceCreator()).create();

其中:

class MyCustomClassInstanceCreator implements JsonDeserializer<MyCustomClass>
{
  @Override
  public MyCustomClass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
  {
    MyCustomClass instance = ...create instance from parameters
    return instance;
  }
}

答案 1 :(得分:0)

试试这个样本

public <T> T readGsonObject(HttpEntity httpEntity, Class<T> tClass) throws Exception {        
        InputStream inputStream = httpEntity.getContent();
        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();
        JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, "utf-8"));
        jsonReader.setLenient(true);
        Object object = gson.fromJson(jsonReader, tClass);
        jsonReader.close();
        inputStream.close();
        return tClass.cast(object);   

}

请致电:

readGsonObject(httpResponse.getEntity(), Integer.class);