1. 程式人生 > >用Gson實現json與物件、list集合之間的相互轉化

用Gson實現json與物件、list集合之間的相互轉化

                先寫一個Person實體類,匯入Gson包

                String jsonData="{\"userid\":\"1881140130\"}";//第一種寫法

                //1.把json轉化為一個類物件
String jsonData="{'userid':'1881140130','username':'三哥','usersex':'男','banji':'計算機1                                     班','phone':'18255052351'}";
Gson gson=new Gson();
Person person=gson.fromJson(jsonData,Person.class);
System.out.println(person.toString());

System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

                // 2.把jsonList轉化為一個list物件
String jsonList="[{'userid':'1881140130','username':'三哥','usersex':'男','banji':'計算機1班','phone':'18255052351'},"
+ "{'userid':'1881140131','username':'蜂','usersex':'男','banji':'計算機1班','phone':'18355092351'},"
+ "{'userid':'1881140132','username':'寶','usersex':'男','banji':'計算機1班','phone':'18955072351'}]";
Gson gson1=new Gson();
List<Person> list= gson1.fromJson(jsonList, new TypeToken<List<Person>>() {}.getType());
for (Person person1 : list) {
System.out.println(person1.toString());
}

 System.out.println("----------------------------");

             //3.把list或物件轉化為json
Gson gson2=new Gson();
String str=gson2.toJson(list);
System.out.println(str);
}

測試結果如下:

Person [userid=1881140130, username=三哥, usersex=男, banji=計算機1班, phone=18255052351]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Person [userid=1881140130, username=三哥, usersex=男, banji=計算機1班, phone=18255052351]
Person [userid=1881140131, username=蜂, usersex=男, banji=計算機1班, phone=18355092351]
Person [userid=1881140132, username=寶, usersex=男, banji=計算機1班, phone=18955072351]
----------------------------
[{"userid":1881140130,"username":"三哥","usersex":"男","banji":"計算機1班","phone":"18255052351"},{"userid":1881140131,"username":"蜂","usersex":"男","banji":"計算機1班","phone":"18355092351"},{"userid":1881140132,"username":"寶","usersex":"男","banji":"計算機1班","phone":"18955072351"}]