在Android中反序列化GSON中的泛型类

时间:2017-09-08 19:59:38

标签: android gson

我有这堂课:

public class DbReturned<T> {
   public boolean State;
   public int UserID;
   public String Error;
   public T row;
   public List<T> Data;
   public boolean Hr;
   public boolean Credits;
}

和Credit类是:

public class Credits {
  public int id;
  public int year;
  public int month;
  public double t1;
  public double t2;
  public double t3;
}

和JSON是

result = {"State":true,"UserID":0,"Error":null,"Data":[{"id":1,"year":2017,"month":1,"t1":77,"t2":88,"t3":99,"CreateBy":1,"CreateDate":"2017-08-22T13:58:27.497","ModifyBy":1,"ModifyDate":"2017-08-22T13:58:27.497"}],"row":null,"Credits":false,"Hr":false}

如何反序列化为DbReturned: 这段代码不起作用:

Gson gson = new GsonBuilder().create();
            if(result != null) {
                DbReturned<Credits> data = gson.fromJson(result, DbReturned.class);
            }

我用过:编译com.google.code.gson:gson:2.4&#39;在gradle中

2 个答案:

答案 0 :(得分:1)

我找到了解决方案:

 public <T> DbReturned<T> getResponse(final Class<T> dataClass ,
                                         final String rawResponse) 
    {
        return gson.fromJson(rawResponse, 
                             getType(DbReturned.class, 
                             dataClass));
    }



private Type getType(final Class<?> rawClass, 
                       final Class<?> 
                       parameterClass) 
   {
        return new ParameterizedType() {
            @Override
            public Type[] getActualTypeArguments() {
                return new Type[]{parameterClass};
            }

            @Override
            public Type getRawType() {
                return rawClass;
            }

            @Override
            public Type getOwnerType() {
                return null;
            }

        };
    }

我称之为:

DbReturned<Credits> data = getResponse(Credits.class , 
                                       result.toString());

并且Gson变量在类顶部是最终的:

public  final  Gson gson = new Gson();

答案 1 :(得分:0)

只需使用

DbReturned<Credits> data = gson.fromJson(result, new DbReturned<Credits>(){}.getType());

为GSON声明完整数据类型。