简体   繁体   English

如何为Gson元帅和Unmarshal创建通用方法?

[英]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. 我试图创建通用的Gson元帅(即gson.toJson())和非元帅(即gson.fromJson())方法。

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 ? 如何在JsonUtil.marshal()中接收类类型并返回String对象?

Please help me to resolve this. 请帮助我解决此问题。 Thanks. 谢谢。

its too late but this solution is working for me to create a generic class for gson : 为时已晚,但是这个解决方案对我来说为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: 您可以使用以下通用gson类:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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