Jersey: @PathParam with commas to List<MyObject>

*爱你&永不变心* 提交于 2019-12-08 17:09:55

问题


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

With a simple Object:

public class MyObject {
    Integer value;
    public MyObject(Integer value) {
        this.value = value;
    }
}

nb: If it possible I don't want to create an MyObjectList which extends List (and have a constructor which split my string)

How may I proceed ?


回答1:


I'm not sure the way of 1,2,3.

If you insist,

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

If you really insist,

annotation,

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
public @interface MyObjectsParam {

}

converter,

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,

@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) {

}


来源:https://stackoverflow.com/questions/28118993/jersey-pathparam-with-commas-to-listmyobject

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