JAX-RS MessageBodyReader

前端 未结 1 1672
囚心锁ツ
囚心锁ツ 2021-02-10 21:09

I\'m learning how the MessageBodyReader method works from the providers. I see the method returns an object and I\'m not sure how to access the object from a service. Could I ge

1条回答
  •  终归单人心
    2021-02-10 22:04

    You misunderstood the purpose MessageBodyReader , it is used for the following purpose :

    Contract for a provider that supports the conversion of a stream to a Java type. To add a MessageBodyReader implementation, annotate the implementation class with @Provider. A MessageBodyReader implementation may be annotated with Consumes to restrict the media types for which it will be considered suitable

    Example : If you have a use case where you getting come custom format other than xml/json ,you want to provide your own UnMarshaller you can use 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;
    
    
    }
    }
    

    In webservice you can use this like ..

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

    More Info : Custom Marshalling/UnMarshalling Example , Jersy Entity Providers Tutorial

    0 讨论(0)
提交回复
热议问题