When to use google Gson's tojson method which accepts type as a parameter? public String toJson(Object src, Type typeOfSrc)

泪湿孤枕 提交于 2019-12-19 10:40:37

问题


I'm trying to convert my object into a JSON String using Gson's toJson API. When I came across 2 different API's which supports the same.

As per Docs -

public String toJson(Object src)

Note that this method works fine if the any of the object fields are of generic type, just the object itself should not be of a generic type. If the object is of generic type, use toJson(Object, Type) instead.

public String toJson(Object src, Type typeOfSrc)

This method must be used if the specified object is a generic type.

I'm using the 1st API which only takes Object as parameter however passing a generic type object and I'm still able to successfully get the JSON string.

Code:

@GET
@Path("/getList")
@Produces(MediaType.APPLICATION_JSON)   
public String getList()     
{       
    Gson gson = new GsonBuilder().create();
    List list = new ArrayList();
    list.add(new Message("kishore", " Bandi "));
    list.add(new Message("test", " values "));
    return gson.toJson(list);   
}

The XML I got as response:

[
    {
        "name": "kishore",
        "text": " Bandi ",
        "dontSend": "Hope not received",
        "iAmEmpty": ""
    },
    {
        "name": "test",
        "text": " values ",
        "dontSend": "Hope not received",
        "iAmEmpty": ""
    }
]

Same is the response even when I used Parameterized type.

Gson gson = new GsonBuilder().create();
        List<String> list = new ArrayList<String>();
        list.add("Kishore");
        list.add("Bandi");
        return gson.toJson(list);

Output:

["Kishore","Bandi"]

So what's the significance of the second API which take type as parameter?


回答1:


The method toJson(Object src, Type typeOfSrc) is used when you are serializing/deserializing a ParameterizedType.

As per docs:

If the object that your are serializing/deserializing is a ParameterizedType (i.e. contains at least one type parameter and may be an array) then you must use the toJson(Object, Type) or fromJson(String, Type) method.


Example (extracted from docs):

Type listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");

Gson gson = new Gson();
String json = gson.toJson(target, listType);
List<String> target2 = gson.fromJson(json, listType);


Question related to ParameterizedType: What is meant by parameterized type?



来源:https://stackoverflow.com/questions/35601355/when-to-use-google-gsons-tojson-method-which-accepts-type-as-a-parameter-publi

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