3

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?

Kishore Bandi
  • 5,537
  • 2
  • 31
  • 52

1 Answers1

4

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?

Community
  • 1
  • 1
Allan Pereira
  • 2,572
  • 4
  • 21
  • 28
  • In my example, I was using Parameterized type and I'm still able to get the json without having the specify the TokenType. ` List list = new ArrayList();` ` list.add("Kishore");` ` list.add("Bandi");` ` return gson.toJson(list);` Output: ["Kishore","Bandi"] So the original API still works even for Parameterized type. – Kishore Bandi Feb 25 '16 at 06:57