我定义了以下jax-rs MessageBodyWriter:
@Provider
@ApplicationScoped
@Produces(MediaType.APPLICATION_JSON)
public class CustomerMessageBodyWriter implements MessageBodyWriter<Customer>
....
}
此外,我的rest-endpoint看起来像这样:
@Path("/api/customers)
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class CustomerService {
@GET
@Path("/{customerNumber})
public Customer getCustomer(@PathParam("customerNumber") String customerNumber) {}
@GET
public List<Customer> getCustomers(){}
}
我希望 CustomerMessageWriter 用于Customer and List<Customer>
响应选项,但我无法找到配置它。
如果它有帮助,我将使用resteasy作为jaxrs实现。
注意:
My Current解决方案是检查List泛型类型。使用完全不同的MessageBodyWriter,因为看起来我不能使用相同的MessageBodyWriter,除非我亲吻仿制品再见:
public boolean isWriteable(@Nonnull final Class<?> type,
@Nonnull final Type genericType,
@Nonnull final Annotation[] annotations,
@Nonnull final MediaType mediaType) {
if (!List.class.isAssignableFrom(type) || !MediaType.APPLICATION_JSON_TYPE.isCompatible(mediaType)) {
return false;
}
if (!(genericType instanceof ParameterizedType)) {
return false;
}
final ParameterizedType parameterizedType = (ParameterizedType) genericType;
final Type actualType = parameterizedType.getActualTypeArguments()[0];
return actualType == Customer.class;
}