【用户中心】写完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个评论
点击登录,快来和大家讨论吧~
表情
图片
暂无评论
听风
下载 APP