用Gson实现json与对象、list集合之间的相互转化
/1.把json转化为一个类对象
String jsonData="{'userid':'1001','username':'张三','usersex':'男','banji':'计算机班','phone':'1008623232'}"; Gson gson=new Gson(); Person person=gson.fromJson(jsonData,Person.class); System.out.println(person.toString());
// 2.把jsonList转化为一个list对象
String jsonList="[{'userid':'1001','username':'张三','usersex':'男','banji':'计算机1班','phone':'1213123'}," + "{'userid':'1002','username':'李四','usersex':'男','banji':'计算机1班','phone':'232323'}," + "{'userid':'1003','username':'王五','usersex':'男','banji':'计算机1班','phone':'432423423'}]"; Gson gson1=new Gson(); List<Person> list= gson1.fromJson(jsonList, new TypeToken<List<Person>>() {}.getType()); for (Person person1 : list) { System.out.println(person1.toString()); }
//3.把list或对象转化为json
Gson gson2=new Gson(); String str=gson2.toJson(list); System.out.println(str);