【问题标题】:How to read JSON request body in Jersey如何在泽西岛读取 JSON 请求正文
【发布时间】:2013-06-27 06:34:29
【问题描述】:

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

例如: 休息资源如下

@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。 但我还需要作为请求的一部分提交的原始 JSON。

谁能帮帮我?

谢谢 ~阿肖克

【问题讨论】:

    标签: jersey jersey-client jersey-1.0


    【解决方案1】:

    这是 Jersey 2.0 的示例,以防万一有人需要它(受未来远程信息处理的启发)。 它拦截 JSON,甚至允许更改它。

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

    【讨论】:

    • 在 isJson() 方法中必须添加检查 (request.getMediaType() == null),在当前版本中它会抛出 NullPointerException。
    【解决方案2】:

    一种可能性是使用 ContainerRequestFilter,它在调用您的方法之前调用

    public class MyRequestFilter 
      implements ContainerRequestFilter {
            @Override
        public ContainerRequest filter(ContainerRequest req) {
                // ... get the JSON payload here
                return req;
            }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-08
      • 2011-10-14
      • 2015-01-05
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 2014-05-22
      相关资源
      最近更新 更多