前后端交互JSON工具类

前后端交互JSON工具类

网络教程中收集的工具类

import com.google.gson.Gson;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Type;

public class HttpUtils<T> {
    public String getJson(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("application/json;charset=utf-8");
        // 获取JSON数据
        ServletInputStream is = req.getInputStream();
        byte[] buffer = new byte[1024];
        StringBuilder sb = new StringBuilder();
        while (is.read(buffer) != -1) {
            sb.append(new String(buffer));
        }
        String json = sb.toString().trim();
        return json;
    }

    public T getBean(HttpServletRequest req, HttpServletResponse resp, Class<T> clazz) throws IOException {
        String json = getJson(req, resp);
        Gson gson = new Gson();
        T t = gson.fromJson(json, clazz);
        return t;
    }

    public T getBean(HttpServletRequest req, HttpServletResponse resp, Type type) throws IOException {
        String json = getJson(req, resp);
        Gson gson = new Gson();
        T t = gson.fromJson(json, type);
        return t;
    }

    public String toJson(Object object) {
        return new Gson().toJson(object);
    }
}

你可能感兴趣的:(前端)