何时使用谷歌Gson的tojson方法接受类型作为参数? public String toJson(Object src,Type typeOfSrc) [英] When to use google Gson's tojson method which accepts type as a parameter? public String toJson(Object src, Type typeOfSrc)
问题描述
我试图使用Gson的toJson API将我的对象转换为JSON字符串。
当我遇到两个支持相同的API时。
$ b
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)
$ b
public String toJson(Object src)
请注意,如果任何对象字段都是泛型类型,则此方法正常工作,只是对象本身不应该是泛型类型。
如果对象是泛型类型,则使用toJson(Object,Type)来代替。
public String toJson(Object src,Type typeOfSrc)
如果指定的对象是一个泛型类型。
This method must be used if the specified object is a generic type.
我使用1st API它只接受Object作为参数,但传递一个泛型类型对象,并且仍然能够成功获取JSON字符串。
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.
代码:
@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);
}
我得到的XML是:
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);
输出:
["Kishore","Bandi"]
那么第二个API类型作为参数?
So what's the significance of the second API which take type as parameter?
推荐答案
方法 toJson(Object src,Type typeOfSrc) code>用于序列化/反序列化
。
根据 docs :
As per docs:
如果序列化/反序列化的对象是
ParameterizedType(即至少包含一个类型参数并且
可能是数组),那么您必须使用toJson(Object,Type)或
fromJson(String,Type)方法。
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);
与 ParameterizedType $相关的问题c $ c>:什么是参数化类型?
这篇关于何时使用谷歌Gson的tojson方法接受类型作为参数? public String toJson(Object src,Type typeOfSrc)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!