Spring Conversion Service:如何将String转换为List<MyType>? [英] Spring Conversion Service: how to convert String to List<MyType>?
问题描述
我正在使用 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;
}
}
现在在我的应用程序中,我可以将 String
转换为 MyType
并且效果很好:
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 控制器中使用相同的转换器,并且它也可以在某种程度上与列表一起使用:
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
,其中包含两个元素.所以spring确实用逗号分割字符串,然后将每个元素分别转换为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));
如果转换服务会自动创建列表会更好,但使用 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<MyType>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!