Using Gson with Maven
<dependencies> <!--Gson:Java to Json conversion--> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8 .0</version> <scope>compile</scope> </dependency> </dependencies>
基础数据类型序列化及反序列化:
Primitives Examples
// Serialization Gson gson = new Gson(); gson.toJson(1); // ==> 1 gson.toJson("abcd"); // ==> "abcd" gson.toJson(new Long(10)); // ==> 10 int[] values = {1}; gson.toJson(values); // ==> [1] // Deserialization int one = gson.fromJson("1", int.class); Integer one = gson.fromJson("1", Integer.class); Long one = gson.fromJson("1", Long.class); Boolean false = gson.fromJson("false", Boolean.class); String str = gson.fromJson("\"abc\"", String.class); String[] anotherStr = gson.fromJson("[\"abc\"]", String[].class);
对象序列化及反序列化:
Object Examples
class BagOfPrimitives { private int value1 = 1; private String value2 = "abc"; private int value3 = 3; BagOfPrimitives() { } } // Serialization BagOfPrimitives obj = new BagOfPrimitives(); Gson gson = new Gson(); String json = gson.toJson(obj); // ==> json is {"value1":1,"value2":"abc","value3":3} // Deserialization BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);// ==> obj2 is just like obj
数组序列化及反序列化
Array Examples
Gson gson = new Gson(); int[] ints = {1, 2, 3, 4, 5}; String[] strings = {"abc", "def", "ghi"}; // Serialization gson.toJson(ints); gson.toJson(strings); // [1,2,3,4,5] //["abc","def","ghi"] // Deserialization int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class);// ==> ints2 will be same as ints String[] string2 = gson.fromJson("[\"abc\", \"def\", \"ghi\"]", String[].class);// ==> string2 will be same as string
集合序列化及反序列化
Collections Examples
Gson gson = new Gson(); Collection<Integer> ints = ImmutableList.of(1,2,3,4,5); // Serialization String json = gson.toJson(ints); // ==> json is [1,2,3,4,5] // Deserialization Type collectionType = new TypeToken<Collection<Integer>>() {}.getType(); Collection<Integer> ints2 = gson.fromJson(json, collectionType); // ==> ints2 is same as ints
泛型类型序列化及反序列化
Serializing and Deserializing Generic Types
static class Bar { private int value1 = 1; private String value2 = "abc"; private int value3 = 3; Bar() {} } static class Foo<T> { private T value; public Foo() {} public Foo(T value) { this.value = value; } } Gson gson = new Gson(); Foo<Bar> bar = new Foo<Bar>(new Bar()); Type fooType = new TypeToken<Foo<Bar>>() {}.getType(); String json = gson.toJson(bar, fooType); Foo<Bar> obj = gson.fromJson(json, fooType); //{"value":{"value1":1,"value2":"abc","value3":3}} //Foo{value=Bar{value1=1, value2='abc', value3=3}}
可参考:https://github.com/google/gson/blob/master/UserGuide.md