Json和Java 对象的互相转换

首先,需要下载一个jar包,名称为:gson-2.2.4.jar。下载地址为:

https://code.google.com/p/google-gson/

必须先引入jar包中相应的类,引入语句为:
import com.google.gson.*;

序列化(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);

对象实例
class BagOfPrimitives {
  private int value1 = 1;
  private String value2 = "abc";
  private transient int value3 = 3;
  BagOfPrimitives() {
    // no-args constructor
  }
}
序列化
BagOfPrimitives obj = new BagOfPrimitives();
Gson gson = new Gson();
String json = gson.toJson(obj);  
==> json is {"value1":1,"value2":"abc"}

反序列化
BagOfPrimitives obj2 = gson.fromJson(json, BagOfPrimitives.class);   
==> obj2 is just like obj


数组实例

Gson gson = new Gson();
int[] ints = {1, 2, 3, 4, 5};
String[] strings = {"abc", "def", "ghi"};

序列化
gson .toJson(ints);      ==> prints [1,2,3,4,5]
gson .toJson(strings);  ==> prints ["abc", "def", "ghi"]

反序列化
int[] ints2 =  gson .fromJson("[1,2,3,4,5]",  int[].class ); 

==> ints2 will be same as ints


Collection
类实例
Gson gson = new Gson();
Collection<Integer> ints = Lists.immutableList(1,2,3,4,5);

序列化
String json = gson.toJson(ints); ==> json is [1,2,3,4,5]

反序列化
Type collectionType = new TypeToken<Collection<Integer>>(){}.getType();
Collection<Integer> ints2 = 
gson.fromJson(json, collectionType);
ints2 is same as ints

你可能感兴趣的:(json,java对象,互相转化)