ImportCom.google.gson.Gson;ImportOrg.apache.struts2.ServletActionContext;Importjavax.servlet.ServletRequest;ImportJava.io.*;/*** Created by Sky.tian on 2015/1/12.*/ Public classTest {Private Static Final intDefault_buffer_size = 1024 * 4; Private Static FinalGson Gson =NewGson (); Public<T> T parserequestbody (class<t> type)throwsIOException {servletrequest request=servletactioncontext.getrequest (); InputStream InputStream=Request.getinputstream (); String JSON=Getrequestbodyjson (InputStream); returnGson.fromjson (JSON, type); } /*** Get the JSON string in the HTTP request body *@paramInputStream *@return * @throwsIOException*/ PrivateString Getrequestbodyjson (InputStream inputstream)throwsIOException {Reader input=NewInputStreamReader (InputStream); Writer Output=NewStringWriter (); Char[] buffer =New Char[Default_buffer_size]; intn = 0; while( -1! = (n =input.read (buffer))) {output.write (buffer,0, N); } returnoutput.tostring (); }}
The user sends an HTTP request to a STRUTS2 action, such as the URL is/user/create, the method is post, and the user's data is placed in the HTTP requestbody.
How do you take the contents of the HTTP body and restore it to the object required by the action? The above code is possible. The Gson library is used.
Get JSON from the body of the HTTP request and deserialize it into an object