简体   繁体   中英

How to create Generic method for Gson marshal and unmarshal?

I am new to Generics.

I tried to create generic Gson marshal (ie, gson.toJson()) and unmarshal (ie, gson.fromJson())methods.

public class Message {
    private MessageBody messageBody;
    ....
}
public class MessageBody {
    private List<BodyParam> bodyParams;
}
public class MessageBodyParam {
    private String name;        
    private Object value;
}

public class JsonUtil {

    //This is not working
    public static <T> String marshal(Object object, Class<T> jtype) {
        Gson gson = new Gson();

        Type type = new TypeToken<T>() {}.getType();
        return gson.toJson(object, type);
    }

    //this is working as expected
    public static <T> T unmarshal(String jsonStr, Class<T> jtype) {
        Gson gson = new Gson();
        Type type = new TypeToken<T>() {}.getType();
        return gson.fromJson(jsonStr, type);
    }
}

I am calling these methods as following:

//Message is my class
String jsonMessage = JsonUtil.marshal(message, Message.class);
Message message = JsonUtil.unmarshal(message, Message.class);

how to receive the class type in JsonUtil.marshal() and return the String object ?

Please help me to resolve this. Thanks.

its too late but this solution is working for me to create a generic class for gson :

public class JSONConversion<T>{

    private  T t;


    public T getT() {
        return t;
    }

    public void setT(T t) {
        this.t = t;
    }

    public String ObjectToString(){

        Gson gson=new Gson();
        return gson.toJson(t);

    }
    public T StringToObject(String jsonString ,Class<T> tt){
        Gson gson=new Gson();
        return gson.fromJson(jsonString, tt);
    }

}

you can use this generic gson class like this:

LoginResponse loginResponse = response.body();
JSONConversion<LoginResponse> jsonConversion=new JSONConversion<>();
jsonConversion.setT(loginResponse);
String createdJson=jsonConversion.ObjectToString());
Log.d("toJson",createdJson);            
LoginResponse convertedObject=jsonConversion.StringToObject(createdJson,LoginResponse.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM