从HTTPrequest的body中拿到JSON并反序列化为一个对象
合集下载
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Reader input = new InputStreamReader(inputStream); Writer output = new StringWriter(); char[] buffer = new char[DEFAULT_BUFFER_SIZE]; int n = 0; while(-1 != (n = input.read(buffer))) {
/** * Created by sky.tian on 2015/1/12. */ public class Test {
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static final Gson gson = new Gson();
}
/** * 得到HTTP请求body中的JSON字符串 * @param inputStream * @return * @throws IOException */ private String getRequestBodyJson(InputStream inputStream) throws IOException {
publiபைடு நூலகம் <T> T parseRequestBody(Class<T> type) throws IOException { ServletRequest request = ServletActionContext.getRequest(); InputStream inputStream = request.getInputStream(); String json = getRequestBodyJson(inputStream); return gson.fromJson(json, type);
请求出错错误代码400请尝试刷新页面重试
从 HTTPrequest的 body中拿到 JSON并反序列化为一个对象
import com.google.gson.Gson; import org.apache.struts2.ServletActionContext;
import javax.servlet.ServletRequest; import java.io.*;
output.write(buffer, 0, n); } return output.toString(); }
}
用户向一个Struts2 Action发送一个HTTP请求,比如URL是/user/create,方法是POST,用户的数据放在HTTP的RequestBody之中。
如何把HTTP body中的内容拿出来还原成Action所需的对象呢?以上代码就可以了。使用了GSON库。
/** * Created by sky.tian on 2015/1/12. */ public class Test {
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
private static final Gson gson = new Gson();
}
/** * 得到HTTP请求body中的JSON字符串 * @param inputStream * @return * @throws IOException */ private String getRequestBodyJson(InputStream inputStream) throws IOException {
publiபைடு நூலகம் <T> T parseRequestBody(Class<T> type) throws IOException { ServletRequest request = ServletActionContext.getRequest(); InputStream inputStream = request.getInputStream(); String json = getRequestBodyJson(inputStream); return gson.fromJson(json, type);
请求出错错误代码400请尝试刷新页面重试
从 HTTPrequest的 body中拿到 JSON并反序列化为一个对象
import com.google.gson.Gson; import org.apache.struts2.ServletActionContext;
import javax.servlet.ServletRequest; import java.io.*;
output.write(buffer, 0, n); } return output.toString(); }
}
用户向一个Struts2 Action发送一个HTTP请求,比如URL是/user/create,方法是POST,用户的数据放在HTTP的RequestBody之中。
如何把HTTP body中的内容拿出来还原成Action所需的对象呢?以上代码就可以了。使用了GSON库。