Jackson反序列化报错:无法将数组值转为单个POJO对象
问题解决:MismatchedInputException 数组反序列化错误
错误根源
API返回的是用户对象数组(JSON格式以[]包裹),但测试代码里尝试将整个响应映射到单个UsersResponseDetails对象,Jackson无法将数组转换成单个对象,因此抛出MismatchedInputException。
解决方案
方案1:直接反序列化为List集合
修改测试代码,将响应映射为List<UsersResponseDetails>类型,RestAssured支持直接通过TypeRef实现集合类型的转换:
@Test(alwaysRun = true, priority = 1) public void getUserDetail() { String url = "http://localhost:8081/users"; RequestSpecification httpRequest = RestAssured.given() .header("Content-Type", "application/json") .contentType(ContentType.JSON); Response response = httpRequest.get(url); ResponseBody responseBody = response.getBody(); // 转换为UsersResponseDetails的List集合 List<UsersResponseDetails> userList = responseBody.as(new TypeRef<List<UsersResponseDetails>>() {}); // 验证第一个用户的id softAssert.assertEquals(userList.get(0).getId(), 1,"invalid"); softAssert.assertAll(); }
方案2:创建包裹类接收数组(需API配合调整)
如果希望用单个对象接收响应,可以创建一个专门的响应包裹类,内部包含用户列表字段:
@Getter @Setter public class UserListResponse { private List<UsersResponseDetails> users; }
修改测试代码:
UserListResponse responseWrapper = responseBody.as(UserListResponse.class); softAssert.assertEquals(responseWrapper.getUsers().get(0).getId(), 1,"invalid");
注意:该方案要求API返回格式调整为
{"users": [/* 用户数组 */]},若API无法修改,优先选择方案1。
验证要点
- 确认API返回的JSON结构是数组(以
[开头),而非单个对象(以{开头) - 确保POJO类字段名与JSON响应字段完全匹配(当前POJO中
OfficeAddress的landMark与响应字段一致,无需调整)
内容的提问来源于stack exchange,提问作者Chathumal Sangeeth
相关产品推荐
相关产品推荐

