JavAndroid

Gson User Guide

Authors: Inderjeet Singh, Joel Leitch, Jesse Wilson

Overview

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson is an open-source project hosted at can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.

Goals for GsonGson Users

Gson was originally created for use inside Google where it is currently used in a number of projects. It is now used by a number of public projects and companies. See details here.

Using Gson

The primary class to use is Gson which you can just create by calling new Gson(). There is also a class GsonBuilder available that can be used to create a Gson instance with various settings like version control and so on.

The Gson instance does not maintain any state while invoking Json operations. So, you are free to reuse the same object for multiple Json serialization and deserialization operations.

Primitives Examples(Serialization)Gson gson = new Gson();gson.toJson(1);==> prints 1gson.toJson(“abcd”);==> prints “abcd”gson.toJson(new Long(10)); ==> prints 10int[] values = { 1 };gson.toJson(values);==> prints [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 Examplesclass BagOfPrimitives { private int value1 = 1; private String value2 = “abc”; value3 = 3; BagOfPrimitives() {// no-args constructor }}(Serialization)BagOfPrimitives obj = new BagOfPrimitives();Gson gson = new Gson();String json = gson.toJson(obj); ==> json is {“value1″:1,”value2″:”abc”}

Note that you can not serialize objects with circular references since that will result in infinite recursion.

(Deserialization)BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class); ==> obj2 is just like objArray Examplesson gson = new Gson();int[] ints = {1, 2, 3, 4, 5};String[] strings = {“abc”, “def”, “ghi”};(Serialization)gson.toJson(ints);==> prints [1,2,3,4,5]gson.toJson(strings); ==> prints [“abc”, “def”, “ghi”](Deserialization)int[] ints2 = gson.fromJson(“[1,2,3,4,5]”, int[].class); ==> ints2 will be same as ints

We also support multi-dimensional arrays, with arbitrarily complex element types

Collections ExamplesGson gson = new Gson();Collection<Integer> ints = Lists.immutableList(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 intsSerializing and Deserializing Generic Types

When you call toJson(obj), Gson calls obj.getClass()to get information on the fields to serialize. Similarly, you can typically pass MyClass.classobject in the fromJson(json, MyClass.class) method. This works fine if the object is a non-generic type. However, if the object is of a generic type, then the Generic type information is lost because of Java Type Erasure. Here is an example illustrating the point:

class Foo<T> { T value;}Gson gson = new Gson();Foo<Bar> foo = new Foo<Bar>();gson.toJson(foo); // May not serialize foo.value correctlygson.fromJson(json, foo.getClass()); // Fails to deserialize foo.value as Bar

The above code fails to interpret value as type Bar because Gson invokes list.getClass() to get its class information, but this method returns a raw class, Foo.class. This means that Gson has no way of knowing that this is an object of type Foo, and not just plain Foo.

You can solve this problem by specifying the correct parameterized type for your generic type. You can do this by using the TypeToken class.

Type fooType = new TypeToken<Foo<Bar>>() {}.getType();gson.toJson(foo, fooType);gson.fromJson(json, fooType);任何的限制,都是从自己的内心开始的。

JavAndroid

相关文章:

你感兴趣的文章:

标签云: