import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum Option {
ADDRESS("address"),
TELEPHONE("telephone");
private String value;
Option(String value) {
this.value = value;
}
@JsonProperty
public String getValue() {
return value;
}
@JsonCreator
public static Option forValue(@JsonProperty("value") String value) {
for (Option o: Option.values()) {
if (o.value.equals(value)) {
return o;
}
}
throw new IllegalArgumentException("Invalid value: " + value);
}
}
给出JSON输入:
{
"value":"address"
}
我希望得到一个ADDRESS枚举,但这不起作用,相反如果我这样做:
@JsonCreator
public static Option forValue(@JsonProperty("value") String value) {
System.out.println(value);
...
}
我找回了一个支架" {"仅限字符(打印到控制台)。 有什么问题?
编辑:
我在Wildfly上使用JAX-RS和Resteasy
@Path("/plans")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class PlanRESTService {
@POST
@Path("/{id:\\d+}/options")
public Response createPlanOption(@PathParam("id") Long id, Option option) {
...
return Response.ok().build();
}
杰克逊注册提供商:
@Provider
public class JacksonContextResolver implements ContextResolver<ObjectMapper> {
private ObjectMapper objectMapper;
public JacksonContextResolver() {
this.objectMapper = new ObjectMapper();
}
@Override
public ObjectMapper getContext(Class<?> aClass) {
return objectMapper;
}
}