Gson

查看

怪盗kidou 你真的会用Gson吗?Gson使用指南(二) Gson UserGuide

fromJson() toJson()


//基本数据类型
Gson gson = new Gson();
int i = gson.fromJson("100", int.class);              //100
double d = gson.fromJson("\"99.99\"", double.class);  //99.99
boolean b = gson.fromJson("true", boolean.class);     // true
String str = gson.fromJson("String", String.class);   // String

Gson gson = new Gson();
String jsonNumber = gson.toJson(100);       // 100
String jsonBoolean = gson.toJson(false);    // false
String jsonString = gson.toJson("String"); //"String"



//POJO类
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);



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

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

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



//Collections 
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);
//TypeToken的构造方法是protected修饰的
//new TypeToken<Collection<Integer>(){}.getType()&

属性重命名 @SerializedName


@SerializedName("email_address")
public String emailAddress;

//or
@SerializedName(value = "emailAddress", alternate = {"email", "email_address"})
public String emailAddress;