[英]JSON Verification rest service
環境:Java,Jersey和Jersey,Tomcat。
我有一個休息服務,從客戶端獲取JSON輸入。 我想驗證輸入(如果是否為JSON,然后為JSON,那么JSON輸入中的鍵是否為預期值)。 如果是,則應產生HTTP 400錯誤請求。
例如-
// 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"應該產生HTTP400。以及具有非正確值的輸入,例如
{“用戶名”:“ abc”,“密碼”:“ abc”}應該產生HTTP 400。
我的代碼適用於上述情況2,但我希望它也適用於情況1。 當存在非json輸入時,我希望它可以將Credential對象設置為null,然后可以在“ if”中使用null對象返回HTTP400。但是事實並非如此。 rest框架可以為這種情況提供什么嗎?
經過長時間的研究,我設法找到了答案。 我們必須在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(); } }
您可以使用gson將JSON轉換為Java對象,然后可以進行驗證
https://code.google.com/p/google-gson/
或者您可以使用Json Lib
http://json-lib.sourceforge.net/index.html
以下方法會有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.