Tuan Anh Hoang-Vu
Tuan Anh Hoang-Vu

Reputation: 1995

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

Upvotes: 5

Views: 6898

Answers (3)

StaxMan
StaxMan

Reputation: 116522

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.

Upvotes: 9

Fredrik Wallenius
Fredrik Wallenius

Reputation: 2872

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.

Upvotes: 1

Fredrik Wallenius
Fredrik Wallenius

Reputation: 2872

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

Upvotes: -1

Related Questions