Search code examples
javajerseyjersey-2.0

jersey - use custom class in URI of resource


I have a custom data class:

public static class Data {
    ...
}

I want to use this class in the URI of a resource in Jersey. For example:

@Path("test")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class ResourceTest {
    @GET
    @Path("/data-{data}")
    public Response get(@PathParam("data") final Data data) {
        ...
    }
}

Is this possible? I guess I need to inject some kind of converter, which converts the textual representation of a Data to a Data instance. I have been looking in the documentation, but haven't found something useful so far.

Ofcourse, I can change this to:

@Path("test")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public class ResourceTest {
    @GET
    @Path("/data-{data}")
    public Response get(@PathParam("data") final String input) {
        final Data data = convert(input);
        ...
    }
}

But I would rather do the conversion elsewhere/automagically wrt. the resource.


Solution

  • From the docs:

    The type of the annotated parameter, field or property must either:

    • ...
    • Have a constructor that accepts a single String argument.
    • Have a static method named valueOf or fromString that accepts a single String argument (see, for example, Integer.valueOf(String)).
    • Have a registered implementation of ParamConverterProvider JAX-RS extension SPI that returns a ParamConverter instance capable of a "from string" conversion for the type.

    So if you provide a constructor Data(String) you should be fine.