JSON Serialize / Deserialize generic type with google-gson

泄露秘密 提交于 2019-12-21 17:23:42

问题


Well, I have to confess I'm not good at generic type in Java

I've written a JSON serialize/deserialize class in C# using JavaScriptSerializer

    private static JavaScriptSerializer js = new JavaScriptSerializer();

    public static T LoadFromJSONString<T>(string strRequest)
    {
        return js.Deserialize<T>(strRequest);
    }

    public static string DumpToJSONString<T>(T rq)
    {
        return js.Serialize(rq);
    }

It works well in C#. Now I'm trying to convert, or atleast, write another JSON serialize/deserialize class in Java. I've tried flexjson and google-gson but I don't know how to specify <T> in Java.

Could someone here help me? Btw, I prefer google-gson


回答1:


In Java you must pass actual type-erased class, not just type parameter, so data binders know what type to use; so something like:

public static T LoadFromJSONString<T>(string strRequest, Class<T> type)
{
    Gson gson = new Gson();
    return gson.fromJson(strRequest, type);
}

but this is usually just needed for deserialization; when serializing, you have an instance with a class which libraries can use.

Btw, one other good Java JSON library you might want to consider using is Jackson; however, for this particular example all libraries you mention should work.




回答2:


After thinking this through I don't think there is a way to solve this as pretty as it is done in your C# code. This because of the type erasure done by the java compiler.

The best solution for you would probably be to use the Gson object at the location where you know the type of the object you need to serialize/deserialize.

If you're not keen on making instances of the Gson object everytime you can of course keep that one static at least, since it doesn't need any type parameters when created.




回答3:


This should work:

import com.google.gson.Gson;
public class GenericClass {

    private static Gson gson = new Gson(); 

    public static <T> T loadFromJSONString(String strRequest)
    {
        return (T) gson.fromJson(strRequest, T.class);
    }

    public static <T> String dumpToJSONString(T rq)
    {
        return gson.toJson(rq);
    }
}


来源:https://stackoverflow.com/questions/4201011/json-serialize-deserialize-generic-type-with-google-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!