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

泪湿孤枕 提交于 2019-12-09 10:07:10

问题


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);

回答1:


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.



来源:https://stackoverflow.com/questions/11825992/spring-conversion-service-how-to-convert-string-to-listmytype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!