【用户中心】写完Delete接口,想测试传入json,报错了,解决方法
删除接口
▼text复制代码@PostMapping("/delete") public BaseResponse<Boolean> deleteUser(@RequestBody Long id, HttpServletRequest request) { if (!isAdmin(request)) { throw new BusinessException(ErrorCode.NO_AUTH); } if (id <= 0) { throw new BusinessException(ErrorCode.PARAMS_ERROR); } boolean b = userService.removeById(id); return ResultUtils.success(b); }
传参
▼POST复制代码Content-Type: application/json { "id": 2 }
返回的信息:
▼text复制代码{ "code": 50000, "data": null, "message": "JSON parse error: Cannot deserialize value of type `long` from Object value (token `JsonToken.START_OBJECT`); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type `long` from Object value (token `JsonToken.START_OBJECT`)\n at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]", "description": "" }
问题解决,codegeex给的方法,问了三四遍终于吐出了正解 方法就是,新建一个类来转换值
1、添加依赖jackson-databind
▼text复制代码<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.3</version> </dependency>
2,新建一个转换器类,来单独处理Long类型的解析
▼text复制代码package com.yang.usercenterbackend.model.domain.request; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import java.io.IOException; public class UserDeleteRequest extends JsonDeserializer<Long> { @Override public Long deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { String idStr = p.getText(); try { return Long.parseLong(idStr); } catch (NumberFormatException e) { throw new IOException("Invalid ID format: " idStr, e); } } }
3、在user类里delete的地方添加注解
▼text复制代码@JsonDeserialize(using = IdDeserializer.class)
4、在controller类传入user,在下文中使用getId获取id进行比较
成功
▼text复制代码@PostMapping("/delete") public BaseResponse<Boolean> deleteUser(@RequestBody User user, HttpServletRequest request) { if (!isAdmin(request)) { throw new BusinessException(ErrorCode.NO_AUTH); } if (user.getId() <= 0) { throw new BusinessException(ErrorCode.PARAMS_ERROR); } boolean b = userService.removeById(user.getId()); return ResultUtils.success(b); }
相关专栏
评论
问答助学
相关内容
0个评论
全部评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论

