Mapping Yes / no for Boolean in a ReST API request parameter

I'm trying to compare yes/no, true/false, Y/Nwith a Boolean query parameter in the URL-address of JAX-RS, but it only displays true/falsesuccessfully, all other values are shown to false all the time.

I understand that when matching url request parameters, jAX-RS tries to find a given data type constructor that takes a string argument and converts the request parameter into an object of the declared data type based on what the constructor does. The Boolean class takes a value true/TRUEas true and treats all other values ​​as false.

Is there any way to match yes/no, Y/Nwith true/false?

+4
source share
1 answer

You can wrap a boolean with regard to QueryParam javadoc . In the following example, I implement 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;
                }
            }
        }
    }
}

Access to /booleanTest?value=yes, /booleanTest?value=yor /booleanTest?value=truewill be returned Result is true, any other value will return Result is false.

+5
source

Source: https://habr.com/ru/post/1568716/


All Articles