Spring Conversion Service:如何将String转换为List< MyType&gt ;? [英] Spring Conversion Service: how to convert String to List<MyType>?

查看:262
本文介绍了Spring Conversion Service:如何将String转换为List< MyType&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Spring的转换服务,并向其注册了自己的转换器:

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

现在在我的应用程序中,我可以进行从StringMyType的转换,并且效果很好:

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

但是我还注意到,例如,我可以在MVC Controller中使用相同的转换器,并且它也可以通过某种方式与列表一起工作:

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 {
    // ....
}

因此,如果我在控制器中提交了param1=value1,value2,则会收到一个包含两个元素的List<MyType>.因此spring确实用逗号分割了String,然后将每个元素分别转换为MyType.是否可以通过编程方式执行此操作?

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?

我需要类似的东西:

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

推荐答案

我自己发现了非常接近的解决方案:

I found pretty close solution myself:

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

如果Conversion Service自动创建列表会更好,但是使用Arrays.asList()自己完成列表并不大.

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.

这篇关于Spring Conversion Service:如何将String转换为List&lt; MyType&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆