How to read JSON request body in Jersey

前端 未结 2 425
广开言路
广开言路 2021-02-08 10:41

I have a requirement, where in i need to read JSON request that is coming in as part of the request and also convert it to POJO at the same time. I was able to convert it to POJ

2条回答
  •  别那么骄傲
    2021-02-08 11:23

    Here is an example for Jersey 2.0, just in case someone needs it (inspired by futuretelematics). It intercepts JSON and even allows to change it.

    @Provider
    public class MyFilter implements ContainerRequestFilter {
    
        @Override
        public void filter(ContainerRequestContext request) {
            if (isJson(request)) {
                try {
                    String json = IOUtils.toString(req.getEntityStream(), Charsets.UTF_8);
                    // do whatever you need with json
    
                    // replace input stream for Jersey as we've already read it
                    InputStream in = IOUtils.toInputStream(json);
                    request.setEntityStream(in);
    
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
    
        }
    
        boolean isJson(ContainerRequestContext request) {
            // define rules when to read body
            return request.getMediaType().toString().contains("application/json"); 
        }
    
    }
    

提交回复
热议问题