日期:2014-05-16  浏览次数:20450 次

Java对象和JSON互转换利器-Gson
Java对象和JSON互转换利器-Gson .
2008-07-11 09:30 3182人阅读 评论(2) 收藏 举报
Gson这个Java类库可以把Java对象转换成JSON,也可以把JSON字符串转换成一个相等的Java对象。Gson支持任意复杂Java对象包括没有源代码的对象。
Gson User Guide
Gson: A library to convert Java Objects to JSON and vice-versa
Inderjeet Singh, Joel Leitch
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 http://code.google.com/p/google-gson. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. Goals for Gson
?Provide easy to use mechanisms like toString() and constructor (factory method) to convert Java to JSON and vice-versa
?Allow pre-existing unmodifiable objects to be converted to and from JSON
?Allow custom representations for objects
?Support arbitrarily complex objects
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 [1] gson.toJson("abcd");       ==> prints ["abcd"] gson.toJson(new Long(10)); ==> prints [10] int[] 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 Examples
class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";   private transient int value3 = 3;
} (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 obj
Finer Points with Objects
?It is perfectly fine (and recommended) to use private fields
?There is no need to use any annotations to indicate a field is to be included for serialization and deserialization. All fields in the current class (and from all super classes) are included by default.
?If a field is marked transient, (by default) it is ignored and not included in the JSON serialization or deserialization.
?This implementation handles nulls correctly
?While serialization, a null field is skipped from the output
?While deserialization, a missing entry in JSON results in setting the corresponding field in the object to null
?If a field is synthetic, it is ignored and not included in JSON serialization or deserialization
?Fields corresponding to the outer classes in  inner classes, anonymous classes, and local classes are ignored and not included in serialization or deserialization
Array Examples
Gson 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", "de