String json = "{\"name\":\"张三\",\"age\":18}";
Gson gson = new Gson();
//转换为集合
Map<String,Object> stuMap = gson.fromJson(json, Map.class);
//如果编写了相应的类也可以转换为指定对象
Student fromJson = gson.fromJson(json, Student.class);
Student stu = new Student("李四", 23);
Gson gson = new Gson();
//{"name":"李四","age":23}
String json = gson.toJson(stu);
Map<String , Object> map = new HashMap<String, Object>();
map.put("name", "孙悟空");
map.put("age", 30);
//{"age":30,"name":"孙悟空"}
String json2 = gson.toJson(map);
List<Student> list = new ArrayList<Student>();
list.add(new Student("八戒", 18));
list.add(new Student("沙僧", 28));
list.add(new Student("唐僧", 38));
//[{"name":"八戒","age":18},{"name":"沙僧","age":28},
{"name":"唐僧","age":38}]
String json3 = gson.toJson(list);
// 如果将一个数组格式的json字符串转换成java对象需要用到
//Gson提供的一个匿名内部类: TypeToken
TypeToken tk= new TypeToken<List<User>>(){};
List<User> list2 = gson.fromJson(json,tk.getType());
System.out.println(list2.get(0));
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Employee> emps = new EmployeeDaoJdbcImpl().getAllEmps();
Gson gson = new Gson();
String jsonStr = gson.toJson(emps);
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(jsonStr);
out.close();
}
function getJsonStr(){
//通过JQuery发送异步请求, 将所有的员工信息通过json的格式返回
$.ajax({
url:"getEmpsJsonStr",
type:"post",
dataType:"json",
success:function(data){ // 会直接将后台返回的json字符串转换成js对象
var str = "<tr><th>Id</th><th>LastName</th><th>Email</th><th>Gender</th></tr>";
for(var i= 0 ;i <data.length;i++){
var emp = data[i];
str+="<tr align='center'><td>"
+emp.id+
"</td><td>"
+emp.lastName+
"</td><td>"
+emp.email+
"</td><td>"
+emp.gender+
"</td></tr>"
}
$("#tb").html(str);
}
});
}
<body>
<input type="button" value="getJsonStr" onclick="getJsonStr();"/>
<table id="tb" border="1px" align="center" width="60%" cellspacing="0px" >
</table>
</body>