您误解了MessageBodyReader的用途,它的用途如下:
支持将流转换为流的提供商的合同
Java 类型。要添加 MessageBodyReader 实现,请注释
带有@Provider的实现类。消息正文阅读器
实现可以用 Consumes 注释来限制媒体
被认为适合的类型
例子 :
如果您有一个用例,您需要自定义格式而不是 xml/json ,您想提供自己的 UnMarshaller,您可以使用 messagebody reader
@Provider
@Consumes("customformat")
public class CustomUnmarshaller implements MessageBodyReader {
@Override
public boolean isReadable(Class aClass, Type type, Annotation[] annotations, MediaType mediaType) {
return true;
}
@Override
public Object readFrom(Class aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap multivaluedMap, InputStream inputStream) throws IOException, WebApplicationException {
Object result = null;
try {
result = unmarshall(inputStream, aClass); // un marshall custom format to java object here
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
在网络服务中你可以像这样使用它。
@POST
@Path("/CreateAccount")
@Consumes("custom format")
public Response createAccount(@Context HttpServletRequest req,Account acc) {
saveAccount(acc); // here acc object is returned from your custom unmarshaller
return Response.ok().build();
}
更多信息:自定义编组/解编组示例 https://github.com/chandu0101/jaxrs-samples/tree/master/custom-marshalling ,
泽西岛实体提供商教程 https://jersey.java.net/documentation/latest/message-body-workers.html