首页 文章

JSON验证休息服务

提问于
浏览
0

Enviorment : Java, Jersey with Jackson, Tomcat.

我有一个休息服务从客户端获取JSON输入 . 我想验证输入,如果它是JSON,然后是JSON,那么JSON输入中的键是否符合预期 . 如果是,那么它应该产生HTTP 400-Bad请求 .

例如-

// REST SERVICE
    @POST
    @Path("login")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response login(Credentials login,
            @Context HttpServletRequest httpRequest) {


        if (login == null)
            // return sendBadRequest(HTTP 400);

        String userName = (String) login.getUsername();
        String passWord = (String) login.getPassword();

        if (userName == null)
            // return sendBadRequest(HTTP 400);
        else if (passWord == null)
            // return sendBadRequest(HTTP 400);


    .....
}

// Credentials.java
@JsonIgnoreProperties(ignoreUnknown=true) 
public class Credentials {

    private String username;

    private String password;

// Getters and setters...
}

例如 - 非json输入之类的

{"key" : "val"

应生成HTTP 400.使用非正确值(如

{"usernames" : "abc", "passwords" : "abc"}

)的输入应生成HTTP 400 .

我的代码适用于提到的案例2,但我预计它也适用于案例1 . 当非json输入存在时,我希望它将Credential对象设置为null,然后我可以将'if'中的null对象返回到HTTP 400.但事实并非如此 . 这个案例是否有其他框架提供的内容?

2 回答

  • 1

    经过长时间的研究,我设法找到了答案 . 我们必须在rest框架中使用@Provider来处理这个错误 .

    这是一个例子:

    @Provider
    public class JsonParseExceptionHandler implements
            ExceptionMapper {
    
        public Response toResponse(JsonParseException exception) {
            ResponseStatus status = new ResponseStatus();
            ClientResponse clientResponse = new ClientResponse();
    
            status.setCode(Status.BAD_REQUEST.getStatusCode());
            status.setMessage(Status.BAD_REQUEST.name());
            status.setFieldName("JSON Parsing Exception");
            status.setFieldDescription(exception.getMessage());
    
            clientResponse.setStatus(status);
    
            return Response
                    .status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode())
                    .entity(clientResponse).build();
        }
    
    }
    
  • -1

    您可以使用gson将JSON转换为java对象,然后您可以验证

    https://code.google.com/p/google-gson/

    或者你可以使用Json Lib

    http://json-lib.sourceforge.net/index.html

    以下方法将有所帮助

    http://json-lib.sourceforge.net/apidocs/jdk15/net/sf/json/util/JSONUtils.html#mayBeJSON(java.lang.String)

相关问题