字符串的 REST 解析枚举失败
REST parsing enum fails for string
a REST URL 允许通过 GET 访问包含枚举值作为查询参数的 url。如果我发送一个包含枚举变量名称的请求,它可以工作,但如果我使用字符串值,它就不会。
示例:通过 [...]cars/1?myEnum=CLIENT
访问有效,但 [...]cars/1?myEnum=Client
无效。为什么?
@XmlType
@XmlEnum
@RequiredArgsConstructor
public enum MyEnum {
@XmlEnumValue("Client")
CLIENT("Client"),
@XmlEnumValue("Server")
SERVER("Server");
@Getter
private final String value;
public static MyEnum fromValue(String v) {
for (MyEnum c : MyEnum.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
客户
@GET
@Path("cars/{myPathParam}")
@Produces(MediaType.TEXT_PLAIN)
public String getCars( //
@PathParam("myPathParam") final String myPathParam,
@QueryParam("myEnum") final MyEnum myEnum) {
return "someValue";
}
问题出在方法的名称上。在我上面的示例中,它是 fromValue
。但是,根据规范(JSR339,第 3.2 章字段和 Bean 属性),它应该是 valueOf
或 fromString
:
Types that have a static method named valueOf
or fromString
with a
single String
argument that return an instance of the type. If both
methods are present then valueOf
MUST be used unless the type is an
enum in which case fromString
MUST be used.
a REST URL 允许通过 GET 访问包含枚举值作为查询参数的 url。如果我发送一个包含枚举变量名称的请求,它可以工作,但如果我使用字符串值,它就不会。
示例:通过 [...]cars/1?myEnum=CLIENT
访问有效,但 [...]cars/1?myEnum=Client
无效。为什么?
@XmlType
@XmlEnum
@RequiredArgsConstructor
public enum MyEnum {
@XmlEnumValue("Client")
CLIENT("Client"),
@XmlEnumValue("Server")
SERVER("Server");
@Getter
private final String value;
public static MyEnum fromValue(String v) {
for (MyEnum c : MyEnum.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
客户
@GET
@Path("cars/{myPathParam}")
@Produces(MediaType.TEXT_PLAIN)
public String getCars( //
@PathParam("myPathParam") final String myPathParam,
@QueryParam("myEnum") final MyEnum myEnum) {
return "someValue";
}
问题出在方法的名称上。在我上面的示例中,它是 fromValue
。但是,根据规范(JSR339,第 3.2 章字段和 Bean 属性),它应该是 valueOf
或 fromString
:
Types that have a static method named
valueOf
orfromString
with a singleString
argument that return an instance of the type. If both methods are present thenvalueOf
MUST be used unless the type is an enum in which casefromString
MUST be used.