SpringMVC接收Post的实体/JSon数据

时间:2020-12-26 04:47:22

接口代码:

@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菜鸟   解决方案也许比较片面或老旧或笨拙    望大神指教

也希望能够帮到遇到同样问题的朋友