Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Conversion Service: how to convert String to List<MyType>?

I am using Spring's Conversion Service, and have my own converter registered with it:

public class MyTypeConverter implements Converter<String, MyType> {
    @Override
    public Currency convert(String text) {
        MyType object = new MyType();
        // do some more work here...
        return object;
    }
}

Now in my application I can do conversion from String to MyType and it works well:

@Autowired
private ConversionService cs;

public void doIt() {
    MyType object = cs.convert("Value1", MyType.class);
}

But I also noticed, for example, that I can use the same converter within my MVC Controller, and it does somehow work with lists too:

@RequestMapping(method = RequestMethod.GET, value = "...")
@ResponseBody
public final String doIt(@RequestParam("param1") List<MyType> objects) throws Exception {
    // ....
}

So if I do submit param1=value1,value2 in controller I do receive a List<MyType> with two elements in it. So spring does split the String by commas and then converts each element separately to MyType. Is it possible to do this programmatically as well?

I would need something similar like this:

List<MyType> objects = cs.convert("Value1,Value2", List<MyType>.class);
like image 366
Laimoncijus Avatar asked Aug 06 '12 09:08

Laimoncijus


People also ask

Does spring convert all values to target data types?

Spring provides out-of-the-box various converters for built-in types; this means converting to/from basic types like String, Integer, Boolean and a number of other types. Apart from this, Spring also provides a solid type conversion SPI for developing our custom converters.

How do I use Conversionservice?

Method SummaryReturn true if objects of sourceType can be converted to the targetType . Return true if objects of sourceType can be converted to the targetType . Convert the given source to the specified targetType . Convert the given source to the specified targetType .

What are converters in Spring MVC and what they do?

Spring 3.0 introduces a simple Converter interface that you can implement and reuse anywhere in Spring. You can use them in Spring MVC to convert request String values to Controller method parameter values of any Object type that you can write a Converter for.

Which of the following annotations support the automatic conversion of exceptions from one type to another?

The @Repository annotation can have a special role when it comes to converting database exceptions to Spring-based unchecked exceptions.


1 Answers

I found pretty close solution myself:

List<MyType> objects = Arrays.asList(cs.convert("Value1,Value2", MyType[].class));

Would be nicer if Conversion Service would create list automatically, but it is not a big overhead to use Arrays.asList() to do it yourself.

like image 77
Laimoncijus Avatar answered Oct 11 '22 18:10

Laimoncijus