SpringMVC接收Post的实体/JSon数据

接口代码:

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

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

 

转载于:https://www.cnblogs.com/JosephBee/p/5670571.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值