JSON使用google-gson序列化/反序列化泛型 [英] JSON Serialize / Deserialize generic type with google-gson

查看:168
本文介绍了JSON使用google-gson序列化/反序列化泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我在C#中使用<$ c编写了一个JSON序列化/反序列化类$ c> 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);
}

它在C#中运行良好。现在我试图转换或至少在Java中编写另一个JSON序列化/反序列化类。我试过 flexjson google-gson ,但我不知道如何指定< T>在Java中。



有人可以帮我吗?顺便说一句,我更喜欢 google-gson

解决方案

不仅仅是类型参数,所以数据绑定器知道使用什么类型;因此类似于:

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

但这通常只需要反序列化;在序列化的时候,你有一个类库的实例。



Btw,你可能要考虑使用的另一个好的Java JSON库是杰克逊;然而,对于这个特定的例子,你提到的所有库都应该有效。


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

解决方案

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.

这篇关于JSON使用google-gson序列化/反序列化泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆