1. 程式人生 > >Gson基礎用法總結

Gson基礎用法總結

      Gson,大家在都知道是json解析工具,也是google的親兒子,自然也有著諸多的優點,今天就來總結一下其詳細的用法,在本篇中將講解其基礎的使用方法,下一篇將講解其高階的用法。

1、基本資料型別解析,例:

Gson gson = new Gson();
int i = gson.fromJson("1", int.class);//1
double d = gson.fromJson("\"1.11\"", double.class);//1.11
double d2 = gson.fromJson("1.11", double.class);//1.11
boolean b = gson.fromJson("true", boolean.class);// true
String s = gson.fromJson("str", String.class);// <span style="font-family: Arial, Helvetica, sans-serif;">str</span>

2、基本資料型別生成,例:

Gson gson = new Gson();
String s1= gson.toJson(1);// 1
String s2= gson.toJson(false);// false
String s3= gson.toJson("str");//"str"

3、實體類的解析及生成,例:

public class User {

    private String name;
    private boolean sex;
    private int age;
    private String homeAddress;
}

User user=new User("小明",true,16,"中國xxxxxxxxxx");
String userJson = gson.toJson(user);
Log.i(TAG,userJson);//{"name":"小明","homeAddress":"中國xxxxxxxxxx","age":16,"sex":true}
User user1 = gson.fromJson(userJson, User.class);
Log.i(TAG,user1.toString());//User{homeAddress='中國xxxxxxxxxx', age=16, sex=true, name='小明'}

4、泛型在Gson中的使用

a、陣列

String jsonss = "[\"aa\",\"bb\",\"cc\"]";
String[] ss = gson.fromJson(jsonss, String[].class);
for (String s:ss) {
     Log.i(TAG,s);
}
String s = gson.toJson(ss);
Log.i(TAG,s);

b、List
List<String> list=gson.fromJson(jsonss, new TypeToken<List<String>>() {}.getType());
<pre name="code" class="java">List<User> list=gson.fromJson(jsonss, new TypeToken<List<<span style="font-family:Arial, Helvetica, sans-serif;">User</span>>>() {}.getType());
c、泛型實際開發中的應用

在開發過程中我們經常遇到伺服器返回:

{"code":"0","message":"success","data":{}}

或者
{"code":"0","message":"success","data":[]}

我們可以定義這樣一個父類
public class BaseBean<T> {
    private String code;
    private Message message;
    private T data;
}
BaseBean<User> userBase=new BaseBean<>("0x00","success",user);
String userStr = gson.toJson(userBase);
Log.i(TAG,userStr);
BaseBean<User> userBase2 = gson.fromJson(userStr, new TypeToken<BaseBean<User>>() {}.getType());
Log.i(TAG,userBase2.toString());

List<User> userList=new ArrayList<>();
userList.add(new User("11",true,23,"中國*******"));
userList.add(new User("22",true,23,"中國*******"));
userList.add(new User("33",true,23,"中國*******"));
userList.add(new User("44",true,23,"中國*******"));
userList.add(new User("55",true,23,"中國*******"));
BaseBean<List<User>> userBeanList=new BaseBean<>("0x00","success",userList);
String userBeanListStr = gson.toJson(userBeanList);
Log.i(TAG,userBeanListStr);
BaseBean<List<User>> o = gson.fromJson(userBeanListStr, new TypeToken<BaseBean<List<User>>>() {}.getType());
Log.i(TAG,o.toString());

至此就已經掌握Gson的基本用法,接一下來將會總結Gson的一些進階的用法。