rsudha
rsudha

Reputation: 307

Mapping Yes/no to Boolean in ReST API query parameter

I am trying to map yes/no, true/false, Y/N to a boolean in JAX-RS url query parameter, but it maps only true/false successfully, all other values are mapped to false all the time.

I understand when mapping the url query parameters, jAX-RS tries to find the given data type constructor that takes the string argument and converts the query parameter to the object of the declared data type based on what the constructor is doing. Boolean class does takes true/TRUE as true and treats all other values as false.

Is there a way to map yes/no, y/n to true/false?

Upvotes: 4

Views: 8084

Answers (2)

Ario
Ario

Reputation: 1940

Using query string boolean just violates single responsibility principle, because you force your function to do more than one thing. I would suggest this style for RESTful:

@GET("/someValue=true")
@GET("/someValue=false")

This means instead of one endpoint you define two :) and in this case any function just focus on its business and there is no need to check false/true.

Upvotes: 0

Bogdan
Bogdan

Reputation: 24590

You could wrap a boolean in something that respects the QueryParam javadoc. In the following example I'm implementing number 3:

@Path("/booleanTest")
public class TestClass {

    @GET
    public String test(@QueryParam("value") FancyBoolean fancyBoolean) {
        String result = "Result is " + fancyBoolean.getValue();
        return result;
    }

    public static class FancyBoolean {
        private static final FancyBoolean FALSE = new FancyBoolean(false);
        private static final FancyBoolean TRUE = new FancyBoolean(true);
        private boolean value;

        private FancyBoolean(boolean value) {
            this.value = value;
        }

        public boolean getValue() {
            return this.value;
        }

        public static FancyBoolean valueOf(String value) {
            switch (value.toLowerCase()) {
                case "true":
                case "yes":
                case "y": {
                    return FancyBoolean.TRUE;
                }
                default: {
                    return FancyBoolean.FALSE;
                }
            }
        }
    }
}

Accessing /booleanTest?value=yes, /booleanTest?value=y or /booleanTest?value=true will return Result is true, any other value will return Result is false.

Upvotes: 5

Related Questions