如何在Jersey中读取JSON请求正文 [英] How to read JSON request body in Jersey

查看:467
本文介绍了如何在Jersey中读取JSON请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,在这里我需要读取作为请求一部分出现的JSON请求,并将其同时转换为POJO.我能够将其转换为POJO对象. 但是我无法获得请求的请求正文(有效负载).

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 POJO object. But I was not able to get the request body (payload) of the request.

例如: 剩余资源如下

@Path("/portal")
public class WebContentRestResource {
    @POST
    @Path("/authenticate")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response doLogin(UserVO userVO) {
        // DO login
        // Return resposne
        return "DONE";
    }
}

POJO为

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class UserVO {
    @XmlElement(name = "name")
    private String username;

    @XmlElement(name = "pass")
    private String password;

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}    

JSON请求为

{ 
  "name" : "name123",
  "pass" : "pass123"
}

能够在WebContentRestResource的doLogin()方法中正确填充UserVO. 但是我还需要作为请求的一部分提交的Raw JSON.

Am able to get UserVO populated properly inside WebContentRestResource's doLogin() method. But i also need the Raw JSON that is submitted as part of the request.

有人可以帮助我吗?

谢谢 〜Ashok

推荐答案

这里是Jersey 2.0的一个示例,以防万一有人需要它(受futuretelematics启发). 它拦截JSON,甚至允许对其进行更改.

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"); 
    }

}

这篇关于如何在Jersey中读取JSON请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆