Mohammad Khir Alsaid
Mohammad Khir Alsaid

Reputation: 223

Deserialize Generic Class in GSON in Android

I have this class :

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

and Credit class is :

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

and JSON is

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}

How to deserialize to DbReturned: this code isn't working :

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

I used : compile 'com.google.code.gson:gson:2.4' in gradle

Upvotes: 1

Views: 69

Answers (2)

Mohammad Khir Alsaid
Mohammad Khir Alsaid

Reputation: 223

I found the solution :

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

        };
    }

and i called it :

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

and the Gson variable is final at top of class :

public  final  Gson gson = new Gson();

Upvotes: 1

Anton Malyshev
Anton Malyshev

Reputation: 8861

Just use

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

to declare full data type for GSON.

Upvotes: 0

Related Questions