How to convert request parameter to the following class

35 Views Asked by At

I've built a small package called option, and I want to integrate it into Spring Boot:

I've created an API with the following code:

@RequestParam(required = false)
Option<String> title,

@RequestParam(required = false)
Option<@jakarta.validation.constraints.Positive Double> width

(The controller class is also annotated via org.springframework.validation.annotation.Validated)

I've tried to make it work with the following code:

@Component
public static class OptionDoubleConverter implements Converter<String, Option<Double>> {
    @Override
    public Option<Double> convert(String source) {
        return Option.of(Double.parseDouble(source));
    }
}

@Configuration
public static class WebConfig implements WebMvcConfigurer {
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new OptionDoubleConverter());
    }
}

public static class OptionValueExtractor implements ValueExtractor<Option<@ExtractedValue ?>> {
    @Override
    public void extractValues(Option<?> originalValue, ValueReceiver receiver) {
        receiver.value(null, originalValue instanceof Some(Object object) ? object : null);
    }
}

@Component
public static class CustomLocalValidatorFactoryBean extends LocalValidatorFactoryBean {
    @Override
    protected void postProcessConfiguration(jakarta.validation.Configuration<?> configuration) {
        super.postProcessConfiguration(configuration);
        configuration.addValueExtractor(new OptionValueExtractor());
    }
}

But with no success…

I'm getting

Failed to convert value of type 'java.lang.String' to required type 'io.github.ashr123.option.Option'; Cannot convert value of type 'java.lang.String' to required type 'io.github.ashr123.option.Option' for property 'title': no matching editors or conversion strategy found

What am I missing?

0

There are 0 best solutions below