SpringMVC接收Post的實體/JSon資料,springmvcjson

來源:互聯網
上載者:User

SpringMVC接收Post的實體/JSon資料,springmvcjson

介面代碼:

@ResponseBody
@RequestMapping(value = "/test",method = RequestMethod.POST)/*只允許POST方式調用此介面*/
public returnType functionName(/*POST資料內容*/@RequestBody parameterType parameterName,HttpServletRequest request) throws Exception {}

 

配置:

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>

 

依賴檔案:

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>

 

邏輯代碼:

/*如果是List資料  在接收到資料之後  需要轉換類型*/

/*否則不需要轉換*/

ObjectMapper mapper = new ObjectMapper();

for (int i = 0; i < behaviorList.size(); i++) {
/*由於用戶端POST過來的List是LinkedHashMap類型的資料
* 所以需要用ObjectMapper進行解析轉換*/

ClassName clazz = mapper.convertValue(List.get(i),ClassName.class);

}

 

實體類:

如果訪問端是C#   DateTime類型要重設為String類型,否則服務端無法解析

 

 

訪問端(C#):

/*POST之前  要先將實體類轉換為JSon字串   然後再轉換成Byte數組*/

 HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(uri);

httpReq.Method = "POST";
httpReq.Accept = "*/*";
httpReq.ContentType = "application/json; charset=utf-8";

byte[] buffer = Encoding.UTF8.GetBytes(dataJsonString);

httpReq.ContentLength = buffer.Length;
httpReq.GetRequestStream().Write(buffer, 0, buffer.Length);

HttpWebResponse httpResp = (HttpWebResponse)httpReq.GetResponse();
Stream respStream = httpResp.GetResponseStream();
StreamReader respStreamReader = new StreamReader(respStream, Encoding.UTF8);
string result = respStreamReader.ReadToEnd();

 

 

以上是個人遇到問題時候     嘗試了一天時間找到的解決辦法    

本人java菜鳥   解決方案也許比較片面或老舊或笨拙    望大神指教 

也希望能夠幫到遇到同樣問題的朋友

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.