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?