泽西岛:@PathParam,用逗号分隔到List< MyObject> [英] Jersey: @PathParam with commas to List<MyObject>
本文介绍了泽西岛:@PathParam,用逗号分隔到List< MyObject>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想用这种模式调用我的Web服务:
I would like to call my Webservice with this pattern :
/resource/1,2,3
在我的课堂上,我想将我的参数绑定到对象列表
And in my Class I want to bind my parameters to a List of Object
@Path("/resource")
public class AppWS {
@GET
@Path("/{params}")
public Response get(@PathParam("params") List<MyObject> params) {
return Response.status(200).entity("output").build();
}
}
使用一个简单的对象:
public class MyObject {
Integer value;
public MyObject(Integer value) {
this.value = value;
}
}
nb:如果可能的话,我不想创建一个扩展List的MyObjectList(并且有一个拆分字符串的构造函数)
nb: If it possible I don't want to create an MyObjectList which extends List (and have a constructor which split my string)
我应该如何进行?
推荐答案
我不确定1,2,3
的方式.
如果您坚持要
private Response get(List<MyObject> params) {
}
@GET
@Path("/{params}")
public Response get(@PathParam("params") String params) {
return get(Stream.of(params.split(","))
.map(MyObject::new)
.collect(Collectors.toList()));
}
如果您真的坚持,
注释
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface MyObjectsParam {
}
转换器
public class MyObjectsParamDateConverter
implements ParamConverter<List<MyObject>> {
@Override
public List<MyObject> fromString(final String value) {
return Stream.of(params.split(","))
.map(MyObject::new)
.collect(Collectors.toList())
}
@Override
public String toString(final List<MyObject> value) {
return value.stream()
.map(o -> o.getValue())
.map(Object::toString)
.collect(Collectors.joining(","));
}
}
提供者,
@Provider
public class MyObjectsParamConverterProvider
implements ParamConverterProvider {
@Override
@SuppressWarnings("unchecked")
default ParamConverter getConverter(final Class<S> rawType,
final Type genericType,
final Annotation[] annotations) {
for (final Annotation annotation : annotations) {
if (MyObjectsParam.class.isInstance(annotation)) {
return new MyObjectsParamDateConverter();
}
}
return null;
}
}
现在您可以像这样使用它了.
Now you can use it like this.
@GET
@Path("/{params}") // still '1,2,3'
public Response get(
@PathParam("params")
@MyObjectsParam // IN ACTION!!!
List<MyObject> params) {
}
这篇关于泽西岛:@PathParam,用逗号分隔到List< MyObject>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文