How to map a http request parameter to an enum in java?

1

I am making an ajax request like this:

$.ajax({
    type : 'POST',
    url : apiURL + '/play',
    dataType : "json",
    data : {
        against : "ANYBODY"
    },
    success : function(data, textStatus, jqXHR) {
        // ...
    },
    error : function(jqXHR, textStatus, errorThrown) {
        // ...
    },
});

And receiving (successfully) the data on the server like this:

@POST
@Path("play")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public Game play(@FormParam("against") String param) {
    Against against = Against.valueOf(param);
    switch(against) {
    case ANYBODY:
    // ...

Notice that Against is a trivial enum:

public enum Against {
    ANYBODY, ANY_FRIEND, A_FRIEND;
}

My question: Is it possible to receive the enum directly, as in the example below? Do you know any changes in the javascript and / or java code that allow me to do this?

@POST
@Path("play")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Game play(Against against) {
    switch(against) {
    case ANYBODY:
    // ...
    
asked by anonymous 15.04.2014 / 22:00

1 answer

2

According to the Jersey documentation , the types used in the parameters annotated with @*Param (as @QueryParam and @FormParam ) should not fall into one of the following:

  • Being a primitive type
  • Have a constructor that accepts a single String argument
  • Have a static method called valueOf or fromString that accepts a single String parameter
  • Have a registered implementation of the SPI extension of JAX-RS javax.ws.rs.ext.ParamConverterProvider that returns an instance of javax.ws.rs.ext.ParamConverter able to do a conversion from a String to the desired type
  • Be a collection as List<T> , Set<T> or SortedSet<T> , where T satisfies items 2 or 3 above.
  • As a Enum , you have the method valueOf . , the same is included in item 2. It would then be perfectly possible to do:

    public Game play(@FormParam("against") Against param) { 
        ...
    }
    

    Update

    There is another solution I usually use with custom types, which is to write a MessageBodyReader to handle automatic deserialization of this type.

    Maybe it's possible to write a generic for enums, but I've never tried.

        
    15.04.2014 / 22:38