11

I have a web API where the user may (or may not) transfer an URL parameter like for example bird, dog etc.

I want this parameter to be mapped to an enum on the server side, something like:

@POST
@Path("/zoo")
public Response createNewAnimal(
                        @QueryParam("animal") 
                        @DefaultValue("CAT") AnimalType type 
                ) throws Exception 

...

public enum AnimalType {
    BIG_BIRD,
    SMALL_CAT;
}

But it doesn't work!

While processing the web request, Enum.valueOf() is being called. And of course it fails, because the bird that user uses as URL parameter doesn't match the identifier in the Enum (AnimalType.BIG_BIRD).

There is no way to override to valueOf() method (it's static...) and setting constructor doesn't help (it's the opposite logical direction).

So maybe you know of a nice solution to this, instead of just using if...else...?

2 Answers 2

19

If you have an enum like:

public enum AnimalType {
    BIG_BIRD, 
    SMALL_CAT, 
    MEDIUM_DOG;
}

then in order for JAX-RS to know what instance to return, your query parameter must be ?animal=BIG_BIRD, ?animal=SMALL_CAT or ?animal=MEDIUM_DOG.

The value of the query parameter is fed to the valueOf static method of the enum to get an instance. Off course, if you send something else like bird it won't match anything and it won't work because @QueryParam expects this:

The type T of the annotated parameter, field or property must either:
- Be a primitive type
- Have a constructor that accepts a single String argument
- Have a static method named valueOf that accepts a single String argument (see, for example, Integer.valueOf(String))
- Be List, Set or SortedSet, where T satisfies 2 or 3 above. The resulting collection is read-only.

The same applies for the @DefaultValue also. You have to specify @DefaultValue("BIG_BIRD"), @DefaultValue("SMALL_CAT") or @DefaultValue("MEDIUM_DOG"):

@POST
@Path("/zoo")
public Response createNewAnimal(
        @QueryParam("animal") 
        @DefaultValue("SMALL_CAT") AnimalType type) {
    // ...
    return Response.ok().entity(type.toString()).build();
}

If you don't want to expose the names on your Java types to the client, you can transform the proper query string value into an enum instance. An if ... else ... if is a very simple way to achieve this but if you want something fancier you could create a wrapper like this:

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class AnimalTypeWrapper {
    private static final Map<String, AnimalType> MAPPER = Collections
            .unmodifiableMap(new HashMap<String, AnimalType>() {
                {
                    put("bird", AnimalType.BIG_BIRD);
                    put("dog", AnimalType.MEDIUM_DOG);
                    put("cat", AnimalType.SMALL_CAT);
                }
            });

    private AnimalType type;

    public static AnimalTypeWrapper valueOf(String value) {
        AnimalType type = AnimalTypeWrapper.MAPPER.get(value.toLowerCase());
        if (type == null) {
            // if nothing found just set the desired default value
            type = AnimalType.SMALL_CAT;
        }
        return new AnimalTypeWrapper(type);
    }

    private AnimalTypeWrapper(AnimalType type) {
        this.type = type;
    }

    public AnimalType getType() {
        return this.type;
    }
}

and in your resource method have:

@POST
@Path("/zoo")
public Response createNewAnimal(
        @QueryParam("animal") 
        AnimalTypeWrapper typeWrapper) {
    // ...
    AnimalType type = typeWrapper.getType();
    return Response.ok().entity(type.toString()).build();
}
3
  • it also accepts classes having a static method named fromString(). I am not sure though what is higher priority fromString() or valueOf(). If fromString() is, then there might not be a need in wrapper class
    – husayt
    Aug 3, 2014 at 13:55
  • 1
    Hey @Bogdan, I wanted to use @DefaultValue by passing like @DefaultValue(String.valueOf(AnimalType.BIG_BIRD.name())) but apparently it does not allow to do that. I am not sure why it would complain. Do you have any idea why it would not be?
    – mkilic
    Aug 6, 2014 at 20:10
  • 6
    @mkilic: annotation attribute values must be compile time constructs. You can't call methods to get the value.
    – Bogdan
    Aug 7, 2014 at 13:13
7

The behavior of enum (de)serialization with JAX-RS and Jackson 2.5.0 tripped me up for a while, so I'm going to try and elaborate on @Bogdan's answer, and show what worked for me.

The thing that wasn't clear to me was that @QueryParam and @FormParam don't follow standard procedure to deserialize enums - so if you're trying to accept an enum as a query param, like so:

@GET
public Response getAnimals(@QueryParam("animalType") AnimalType animalType) {}

...then the only way your animalType argument will be deserialized properly is if your type T (in our case, AnimalType) satisfies one of the following properties:

  1. Be a primitive type.
  2. Have a constructor that accepts a single String argument.
  3. Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String)).
  4. Have a registered implementation of ParamConverterProvider JAX-RS extension SPI that returns a ParamConverter instance capable of a "from string" conversion for the type.
  5. Be List<T>, Set<T> or SortedSet<T>, where T satisfies 2, 3 or 4 above. The resulting collection is read-only.

...per the Java EE 7 @QueryParam docs.

This means that, in addition to implementing custom (de)serialization for your normal use cases, you will also need to satisfy one of the five conditions listed above. Then, and only then!, you'll be able to handle the @QueryParam deserialization case.

The solution...

A simple way that I found to handle both the normal (de)serialization cases and the @QueryParam case is to a) satisfy condition #3 by implementing fromString(), and b) implement a mapper class that contains both a serializer and a deserializer, the latter of which will rely on fromString(), so we have consistent deserialization:

// Our example enum class...

@JsonSerialize(using = AnimalTypeMapper.Serializer.class)
@JsonDeserialize(using = AnimalTypeMapper.Deserializer.class)
public enum AnimalType {
  CAT("cat"),
  BIRD("bird"),
  DOG("doggy");

  private final String name;

  AnimalType(String name) {
    this.name = name;
  }

  private static Map<String, AnimalType> VALUES_BY_NAME = Arrays.stream(values())
    .collect(Collectors.toMap(AnimalType::getName, Function.identity()));

  public String getName() {
    return name;
  }

  // Implementing this method allows us to accept AnimalType's as @QueryParam
  // and @FormParam arguments. It's also used in our custom deserializer.
  public static AnimalType fromString(String name) {
    return VALUES_BY_NAME.getOrDefault(name, DOG);
  }
}

// Our custom (de)serialization class...

public class AnimalTypeMapper {
  public static class Serializer extends JsonSerializer<AnimalType> {
    @Override
    public void serialize(AnimalType animalType, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
      jsonGenerator.writeString(animalType.getName());
    }
  }

  public static class Deserializer extends JsonDeserializer<AnimalType> {
    @Override
    public AnimalType deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
      return AnimalType.fromString(jsonParser.getValueAsString());
    }
  }
}

Hopefully someone out there will find this helpful. I spent way too much time spinning my wheels on this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.