先写一个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"}]
————————————————