简单的使用Gson (序列化 和 反序化)
下载地址:http://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.5
在项目导入jar包后
package com.web; import com.dao.BookInMemoryDAO; import com.entity.Book; import com.google.gson.Gson; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/book/text") public class ServletTest extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置请求编码 request.setCharacterEncoding("utf-8");
//设置响应数据格式 response.setContentType("application/json;charset=utf-8");
//设置响应请求 response.setCharacterEncoding("utf-8"); //获取数据 List<Book> books = new BookInMemoryDAO().listAll();
//将数据转为json格式
//调用Gson的方法 String s = new Gson().toJson(books);
//将数据渲染出去 response.getWriter().print(s); } }
运行结果:
示例:
1 public List<Car> listCars() { 2 //借助redis的高效能力,让redis作为数据的缓存 3 4 //打开 redis 5 Jedis jedis = new Jedis(); 6 //json 序列化 7 Gson gson = new Gson(); 8 //判断 redis 中 有没有 这个 键值 有的话,直接取 redis 中的数据 9 if (jedis.exists("cars")) { 10 List<Car> cars = gson.fromJson(jedis.get("cars"), new TypeToken<List<Car>>() {}.getType()); 11 return cars; 12 } 13 //去数据库中 查询 14 List<Car> cars = car.listCars(); 15 //存储到redis中 16 jedis.set("cars",gson.toJson(cars)); 17 18 return cars; 19 }
结果:
1 [Car{id=1, name='宝马', speed=6.34}, Car{id=2, name='悍马', speed=8.4}, Car{id=3, name='大魔王', speed=8.8}]