Api文档:http://www.javadoc.io/doc/com.google.code.gson/gson/2.8.0
This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking toJson(Object) or fromJson(String, Class) methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple threads.
You can create a Gson instance by invoking new Gson() if the default configuration is all you need. You can also use GsonBuilder to build a Gson instance with various configuration options such as versioning support, pretty printing, custom JsonSerializers, JsonDeserializers, and InstanceCreators.
Here is an example of how Gson is used for a simple Class:
Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target = new MyType();
String json = gson.toJson(target); // serializes target to Json
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
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) orfromJson(String, Type) method. Here is an example for serializing and deserializing a ParameterizedType:
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);

本文介绍了Gson库的基本用法,包括如何构造Gson实例、序列化和反序列化的操作等。并提供了针对泛型类型的序列化和反序列化示例。
679

被折叠的 条评论
为什么被折叠?



