SpringMVC接口测试异常:Can not deserialize instance of int out of START_OBJECT token
之前使用springmvc搭建了restful风格的接口服务,在使用mockmvc进行集成测试的时候出现了异常:Can not deserialize instance of int out of START_OBJECT token。为什么会出现这个问题?怎么解决这个问题呢?接下来本文详细分析讲解这个问题。
一、问题展现
- 接口代码
@ResponseBody
@RequestMapping(value = "/m1", method = RequestMethod.POST)
@ApiOperation(value = "测试方法1", httpMethod = "POST", response = ApiResult.class, notes = "测试方法1")
public ApiResult method1(@ApiParam(required = true, name = "p1", value = "参数1") @RequestBody String p1,
@ApiParam(required = true, name = "p2", value = "参数2") @RequestBody Integer p2) throws Exception {
String content = "p1=" + p1 + ", p2=" + p2;
System.out.println(content);
ApiResult<String> result = new ApiResult<String>();
result.setCode(ResultCode.SUCCESS.getCode());
result.setData(content);
return result;
}
- 测试代码
@Test
public void method1Test() throws Exception {
Map<String, Object> params = new HashMap<String, Object>();
params.put("p1", "x001");
params.put("p2", 10010);
ObjectMapper mapper = new ObjectMapper();
byte[] content = mapper.writeValueAsBytes(params);
this.mockMvc.perform(post("/activation/m1").contentType(APPLICATION_JSON_UTF8).content(content).accept(APPLICATION_JSON_UTF8))
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
.andExpect(jsonPath("$.code").value(2000))
.andDo(print());
}
- 执行上述测试代码控制台异常错误
Caused by: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of int out of START_OBJECT token at [Source: org.springframework.mock.web.DelegatingServletInputStream@3e0fa1; line: 1, column: 1]
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.mappingException(DeserializationContext.java:762)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer._parseInteger(StdDeserializer.java:419)
at com.fasterxml.jackson.databind.deser.std.NumberDeserializers$IntegerDeserializer.deserialize(NumberDeserializers.java:289)
at com.fasterxml.jackson.databind.deser.std.NumberDeserializers$IntegerDeserializer.deserialize(NumberDeserializers.java:271)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3066)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2221)
at org.springframework.http.converter.json.MappingJackson2HttpMessageConverter.readJavaType(MappingJackson2HttpMessageConverter.java:168)
... 50 more
二、分析问题
我们先从接口方法中参数注解@RequestBody说起吧!我们大家都知道@ResponseBody是把接口方法返回结果转化成JSON形式提供给方法调用者,那么相对应的,@RequestBody是把客户端POST请求content部分转化成JavaBean对象或者JSON对象。@RequestBody的解析有两个条件:
- POST请求中content的值必须为json格式(存储形式可以是字符串,也可以是byte数组);
- 被@RequestBody注解的参数类型必须是完全可以接收参数值的类型,比如:Map,JSONObject,或者对应的JavaBean;
@RequestBody将post请求中content值转为一个整体对象,该对象包含所有参数名和参数值,所以接口方法必须也是一个参数完全接收所有参数名和参数值。
根据上面展示的代码来看,@RequestBody将params对象json形式内容转换成一个整体参数值,无论是p1还是p2,都无法接收该参数值。
三、解决问题
在method1方法中定义一个可以接收整体参数值的对象类型即可,通常可选类型有:Map、JSONObject和JavaBean,JSONObject相对于Map,其取值方法更灵活。下面我们将在method1方法中定义一个JSONObject类型的参数。
@ResponseBody
@RequestMapping(value = "/m1", method = RequestMethod.POST)
@ApiOperation(value = "测试方法1", httpMethod = "POST", response = ApiResult.class, notes = "测试方法1")
public ApiResult method1(@ApiParam(required = true, name = "p", value = "参数") @RequestBody JSONObject p) throws Exception {
String content = "p1=" + p.getString("p1") + ", p2=" + p.getInt("p2");
System.out.println(content);
ApiResult<String> result = new ApiResult<String>();
result.setCode(ResultCode.SUCCESS.getCode());
result.setData(content);
return result;
}
测试响应结果正常:
MockHttpServletResponse:
Status = 200
Error message = null
Headers = {Content-Type=[application/json;charset=UTF-8]}
Content type = application/json;charset=UTF-8
Body = {"code":2000,"message":"","data":"p1=x001, p2=10010"}
Forwarded URL = null
Redirected URL = null
Cookies = []
四、扩展
对POST接口的请求可以采取表单式和接口客户端式两种方法提交。
表单式提交
参数形式:p1=v1&p2=v2,服务端接口方法获取参数可以采用@RequestParam注解对应参数方式。客户端提交
这里的客户端具体指自定义编码的客户端。将所有参数信息组织成一个整体对象,然后转换成json对象,设置为post请求content的值,提交到服务端。此时服务端接口方法获取参数即需要采用本文讨论的方式。其实本文method1方法也可以自定义一个包含p1和p2两个字段的JavaBean类型,自己可以尝试一下,呵呵!
http://javatech.wang/index.php/archives/82/
SpringMVC接口测试异常:Can not deserialize instance of int out of START_OBJECT token的更多相关文章
- JSON parse error: Cannot deserialize instance of `int` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc
代码程序: @PostMapping("selectById") @ResponseBody public Result selectById(@RequestBody int i ...
- Can not deserialize instance of xxx out of START_ARRAY token
Json 反序列化异常 Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableEx ...
- Jackson反序列化提示:Can not deserialize instance of Task out of START_ARRAY token
解决方法: 1.没有绝对的方法,只能不断的测试和排查. 2.检查一下JSON数据和实体的字段结构是不是不一致导致的.比如JSON数据是数组,而实体字段为非数组. 参考: https://stackov ...
- 关于fasterxml-jackson发生Can not deserialize instance of异常原因验证
关于fasterxml-jackson发生Can not deserialize instance of异常原因验证 这两天线上有大量的java.lang.IllegalArgumentExcepti ...
- JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of j
异常信息如下: JSON parse error: Can not deserialize instance of java.lang.String out of START_OBJECT token ...
- SpringMVC 处理异常的4种方式
springmvc处理异常有三种方式: 1.在一个controller中定义一个方法,用@ExceptionHandler注解标注.(优先级最高) @ExceptionHandler public M ...
- springmvc 通过异常增强返回给客户端统一格式
在springmvc开发中,我们经常遇到这样的问题:逻辑正常执行时返回客户端指定格式的数据,比如json,但是遇NullPointerException空指针异常,NoSuchMethodExcept ...
- Could not read document: Can not deserialize instance of java.lang.String out of START_ARRAY
线上问题: { "timestamp": "1544510665", "status": 400, "error": & ...
- 解决用户自生成meta导入kylin后报错问题Can not deserialize instance of java.lang.String[] out of VALUE_STRING token
报错栈: -- ::, ERROR [http-bio--exec-] cube.CubeManager: : Error during load cube instance, skipping : ...
随机推荐
- The content of elements must consist of well-formed character data or markup
java 中使用dom4j解析含有特殊字符的xml文件出现了如题的错误 这个时候需要在特殊字符外面加上 <![CDATA[ /6169220648+20671/1>7+-47390045& ...
- C语言之linux内核实现平方根计算算法
关于平方根的计算,在linux内核中也有实现,就像math.h数学库里的sqrt这个函数一样. 平方根的公式定义: 如果一个非负数x的平方等于a,即 , ,那么这个非负数x叫做a的算术平方 ...
- Android热补丁技术—dexposed原理简析(手机淘宝采用方案)
上篇文章<Android无线开发的几种常用技术>我们介绍了几种android移动应用开发中的常用技术,其中的热补丁正在被越来越多的开发团队所使用,它涉及到dalvik虚拟机和android ...
- sqlite 数据类型 <转>
一般数据采用的固定的静态数据类型,而SQLite采用的是动态数据类型,会根据存入值自动判断.SQLite具有以下五种数据类型: 1.NULL:空值.2.INTEGER:带符号的整型,具体取决有存入数字 ...
- js正则表达式中test,exec,match方法的区别说明
js正则表达式中test,exec,match方法的区别说明 test test 返回 Boolean,查找对应的字符串中是否存在模式.var str = "1a1b1c";var ...
- spring中一些aware接口
Spring中提供一些Aware相关接口,像是BeanFactoryAware. ApplicationContextAware.ResourceLoaderAware.ServletContextA ...
- android传值
需求 OneActivity向TwoActivity传值name=hzs,然后TwoActivity向OneActivity传值sex=Y 第一步:OneActivity向TwoActivity传值n ...
- Day8 接口与归一化设计
接口:在程序的使用中,我不能把程序的主体直接提供给使用者,一般是提供一个接口. 为什么要使用接口: 1,接口提取了一群共同的函数,可以把接口当做一个函数的集合. 2,让子类去实现接口中的函数. 归一化 ...
- Angular6.0发布
Angular v6 新版本重点关注工具链以及工具链在 Angular 中的运行速度问题. Angular v6 是统一整体框架.Material 和 CLI 三大 Angular 组件的第一个版本, ...
- Apache Solr vs Elasticsearch
http://solr-vs-elasticsearch.com/ Apache Solr vs Elasticsearch The Feature Smackdown API Feature Sol ...