前後交互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);
    }
}