Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Serialize / Deserialize generic type with google-gson

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

like image 779
Tuan Anh Hoang-Vu Avatar asked Nov 17 '10 02:11

Tuan Anh Hoang-Vu


2 Answers

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.

like image 78
StaxMan Avatar answered Sep 29 '22 02:09

StaxMan


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.

like image 24
Fredrik Wallenius Avatar answered Sep 29 '22 03:09

Fredrik Wallenius