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

Asked

Viewed 504 times

1

I’m making an ajax requisition 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:
    // ...

Note that Against is a trivial Enum:

public enum Against {
    ANYBODY, ANY_FRIEND, A_FRIEND;
}

My doubt: is it possible to receive Enum directly, as in the example below? Do you know any changes in 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:
    // ...

1 answer

2


According to the jersey documentation, the types used in the parameters annotated with @*Param (as @QueryParam and @FormParam) must not fit in one of the following items:

  1. To be a primitive kind
  2. Have a constructor that accepts a single argument String
  3. Have a static method called valueOf or fromString accepting a single String parameter
  4. Have a registered implementation of the JAX-RS SPI extension javax.ws.rs.ext.ParamConverterProvider which returns an instance of javax.ws.rs.ext.ParamConverter capable of converting a String to the desired type
  5. Being a Collection like List<T>, Set<T> or SortedSet<T>, where T satisfy items 2 or 3 above.

As a Enum has the method valueOf, the same fits in item 2. Soon it would be perfectly possible to do:

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

Updating

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

It may be possible to write a generic for enums, but I have never tried.

  • It doesn’t exactly look like I wanted it to, because I still have to keep the MediaType.APPLICATION_FORM_URLENCODED and the @FormParam, but already improves considerably. Thank you.

  • @André I added one more option. See if you can help. Unfortunately I’m a little out of time to make a functional example, but if you can understand how the MessageBodyReader, will probably solve your problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.