简体   繁体   English

HttpMessageNotReadableException:JSON 解析错误:无法从字符串反序列化“int”类型的值

[英]HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `int` from String

How to show conversion error along with other validation errors when creating REST API?创建 REST API 时如何显示转换错误以及其他验证错误?

  • Spring Boot Spring 开机
  • Spring MVC Spring MVC
  • REST Controller REST Controller
@Data
@AllArgsConstructor
class DTO
{
    @NotNull
    @Min(1)
    private Integer id;
}

@RestController
class ExampleController
{
    @PostMapping("/")
    public void createEndpoint(@Valid @RequestBody DTO dto) {
        return "{\"message\": \"OK\"}";
    }
}

When I make request to this endpoint,当我向这个端点发出请求时,

POST /
{
    "id: "abrakadabra"
}

I would like to get something like this我想得到这样的东西

{
    "errors": {
        "id": [
            { code: "invalid_format", message: "Field must contain only digits" }
        ]
    }
}

What I actually get?我实际上得到了什么?

Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `int` from String "abrakadabra": not a valid `int` value;
nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `int` from String "abrakadabra": not a valid `int` value
at [Source: (PushbackInputStream); line: 2, column: 24] (through reference chain: com.mylid.back.dtos.CreateCompanyDto["pricing_plan_id"])]

I know that I can create custom annotation for validation.我知道我可以创建自定义注释进行验证。 BUT the problem is that the process does not reach validation.但问题是该过程没有达到验证。 It fails on deserialization step.它在反序列化步骤中失败。

[Possible way] [可能的方式]

There is one dirty trick, to change Integer type in DTO to String.有一个肮脏的技巧,将 DTO 中的 Integer 类型更改为字符串。 Create custom annotation to check if String contains only digits.创建自定义注释以检查字符串是否仅包含数字。 Then manually map this String from DTO to Integer in Entity.然后在Entity中手动map这个String从DTO到Integer。 Then save to database.然后保存到数据库。

What are other ways how to solve this problem?还有什么其他方法可以解决这个问题? It is very weird, that there is a few topics on Google and StackOverFlow for this particular problem.很奇怪,在 Google 和 StackOverFlow 上有一些针对这个特定问题的主题。 And on almost every page the accepted answer is "it is not our problem, API clients should pass integer".在几乎每一页上,接受的答案都是“这不是我们的问题,API 客户端应该传递整数”。

In PHP we can easily do it with 'integer' validator, almost every framework has it, and it will not prevent other fields from validation if I pass "abracadabra" instead of "1".在 PHP 中,我们可以使用“整数”验证器轻松完成,几乎每个框架都有它,如果我通过“abracadabra”而不是“1”,它不会阻止其他字段的验证。

What about implementing a custom type?实现自定义类型怎么样?

For example (the code below is crap, missing null handling and so on - just wanted to show you the idea)例如(下面的代码是废话,缺少 null 处理等等 - 只是想向您展示这个想法)

public class DTOId {
    final Integer value;

    private DTOId(String value) {
        Assert.hasText(value, "Value for DTOId should not not be null or empty!");
        // Validation that it is a integer, min value and so on
        this.value = Integer.valueOf(value);
    }

    @JsonCreator
    public static DTOId of(final String value) {
        return new DTOId(value);
    }

    @JsonValue
    public String toString() {
        return value.toString();
    }
}

Then you could use然后你可以使用

@Data
@AllArgsConstructor
class DTO
{
    @NotNull
    private DTOId id;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JSON 解析错误:无法从字符串反序列化“java.time.LocalDateTime”类型的值 - JSON parse error: Cannot deserialize value of type `java.time.LocalDateTime` from String HttpMessageNotReadableException:JSON 解析错误:无法构造实例 - HttpMessageNotReadableException: JSON parse error: Cannot construct instance 面对 JSON 解析问题,无法从数组值 jackson.databind.exc.MismatchedInputException 反序列化类型为“java.lang.String”的值 - Facing JSON parse issue, Cannot deserialize value of type `java.lang.String` from Array value jackson.databind.exc.MismatchedInputException Json InvalidFormatException:无法从字符串“flush”反序列化 HandType 类型的值 - Json InvalidFormatException : Cannot deserialize value of type HandType from String "flush" 无法从字符串反序列化int类型的值 - Can not deserialize value of type int from String JSON 解析错误:无法反序列化 `java.time.LocalTime` 类型的值 - JSON parse error: Cannot deserialize value of type `java.time.LocalTime` 无法从 String 反序列化 LocalDateTime 类型的值 - Cannot deserialize value of type LocalDateTime from String Spring 开机 JSON 解析错误:无法反序列化值 - Spring boot JSON parse error : Cannot deserialize value “JSON 解析错误:无法构造实例(尽管至少存在一个 Creator):无法从 Object 值反序列化 - SpringBoot - "JSON parse error: Cannot construct instance of (although at least one Creator exists): cannot deserialize from Object value - SpringBoot JSON 解析错误:无法反序列化 ArrayList 的实例 - JSON parse error: Cannot deserialize instance of ArrayList
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM