Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top