簡體   English   中英

澤西島:@PathParam用逗號列表<MyObject>

[英]Jersey: @PathParam with commas to List<MyObject>

我想用這種模式調用我的Webservice:

/resource/1,2,3

在我的類中,我想將我的參數綁定到對象列表

@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(並且有一個分割我的字符串的構造函數)

我該怎么辦?

我不確定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;
    }
}

現在你可以像這樣使用它。

@GET
@Path("/{params}") // still '1,2,3'
public Response get(
    @PathParam("params")
    @MyObjectsParam // IN ACTION!!!
    List<MyObject> params) {

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM