赞
踩
package com.hmdp.utils; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RequestWithJsonUtil { private HttpServletRequest request; public RequestWithJsonUtil(HttpServletRequest request) { this.request = request; } //获取一个字符串格式的 public String getString(String key) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuilder stringBuilder = new StringBuilder(); String line= null; while ((line=reader.readLine())!=null){ stringBuilder.append(line); } String response = stringBuilder.toString(); JSONObject jsonObject = JSONUtil.parseObj(response); String result = jsonObject.getStr(key); return result; } //获取任意格式的 public Object get(String key) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuilder stringBuilder = new StringBuilder(); String line= null; while ((line=reader.readLine())!=null){ stringBuilder.append(line); } String response = stringBuilder.toString(); JSONObject jsonObject = JSONUtil.parseObj(response); Object result = jsonObject.get(key); return result; } }
我们在使用的时候,只需要new出该工具对象并且传入request对象(HttpServltRequest),调用get或getString方法,写入想要获得的key即可。
RequestWithJsonUtil map = new RequestWithJsonUtil(request);
int type = (int) map.get("type");
return type;
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。