If a Java class is a generic type and we are using it with the Gson library for JSON serialization and deserialization. The Gson library provides a class called com.google.gson.reflect.TypeToken to store generic types by creating a Gson TypeToken class and pass the class type. Using this type, Gson can able to know the class passed in the generic class.
public class TypeToken<T> extends java.lang.ObjectExample
import java.lang.reflect.Type;
import java.util.*;
import com.google.gson.*;
import com.google.gson.reflect.*;
public class GenericTypesJSONTest {
public static void main(String[] args) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
List<String> list = Arrays.asList("INDIA", "AUSTRALIA", "ENGLAND", "SOUTH AFRICA");
String jsonStr = gson.toJson(list);
System.out.println(jsonStr);
Type listType = new TypeToken<List<String>>() {}.getType();
list = gson.fromJson(jsonStr, listType);
System.out.println(list);
}
}
输出
[
"INDIA",
"AUSTRALIA",
"ENGLAND",
"SOUTH AFRICA"
]
[INDIA, AUSTRALIA, ENGLAND, SOUTH AFRICA]
以上就是如何使用Java中的Gson库对泛型类型进行序列化和反序列化?的详细内容,更多请关注编程之家其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。