枚举作为 Spring Boot Rest 中的请求参数
Enums as Request Parameters in Spring Boot Rest
我是 spring 引导新手,正在尝试使用 Enum 作为休息请求的参数。
这是我的枚举 class:
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
}
在我的控制器中class我正在使用这个方法:
@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]]
您的正文被声明为简单枚举类型,而不是对象。因此,不要 posting JSON 带有大括号的对象,而是尝试 post 只有一个值,例如:
"JANUARY"
我是 spring 引导新手,正在尝试使用 Enum 作为休息请求的参数。
这是我的枚举 class:
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
}
在我的控制器中class我正在使用这个方法:
@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]]
您的正文被声明为简单枚举类型,而不是对象。因此,不要 posting JSON 带有大括号的对象,而是尝试 post 只有一个值,例如:
"JANUARY"