【问题标题】:Enums as Request Parameters in Spring Boot Rest枚举作为 Spring Boot Rest 中的请求参数
【发布时间】:2019-10-07 13:07:42
【问题描述】:

我是 Spring Boot 新手,并尝试使用 Enum 作为休息请求的参数。

这是我的枚举类:

public enum Month {

    JANUARY (1, "january"), FEBRUARY(2,"february"), MARCH(3,"march"),
    APRIL(4,"april"), MAY(5,"may"), JUNE(6,"june"), JULY(7,"july"),
    AUGUST(8, "august"), SEPTEMBER(9,"september"), OCTOBER(10,"october"),
    NOVEMBER(11,"november"), DECEMBER(12,"december");

    private String desc;
    private int id;

    //Constructure

    //Getters and Setters
}

在我的控制器类中,我正在使用这种方法:

    @RequestMapping(value = "/testmonth", method = RequestMethod.POST)
        public Month TestForMonth(@RequestBody Month inputPayload) {
            Month response = inputPayload;
            response.setId(inputPayload.getId());
            response.setDesc(inputPayload.getDesc());
            System.out.println("As String: " + inputPayload.getDesc() + ". As int " + inputPayload.getId() + ".");
            return response;
        }

这是我的 JSON:

{
    Month: "JANUARY"
}

但它不起作用..我收到此错误:

.w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `com.example.simplerestapis.models.Month` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.example.simplerestapis.models.Month` out of START_OBJECT token
 at [Source: (PushbackInputStream); line: 1, column: 1]]

【问题讨论】:

  • 看起来像是格式错误的请求正文。我认为您的请求不是 json。尝试发布类似“JANUARY”的内容(带引号)。
  • 请同时添加您请求的 JSON 负载。
  • @Arnaud 谢谢你让我知道。
  • 只尝试不带括号的“JANUARY”
  • @merdle 我很高兴 :) 我将其发布为答案,以便您对其进行投票。

标签: java rest spring-boot spring-restcontroller request-mapping


【解决方案1】:

你的 body 被声明为简单的枚举类型,而不是对象。因此,不要使用大括号发布 JSON 对象,而是尝试仅发布一个值,例如:

"JANUARY"

【讨论】:

    猜你喜欢
    • 2017-09-01
    • 1970-01-01
    • 2018-02-15
    • 2017-10-26
    • 2019-07-22
    • 2020-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多