简体   繁体   English

杰克逊解析 JSON

[英]Parsing JSON by jackson

I have a form where the parameters packed in JSON are parsed by Jackson.我有一个表单,其中打包在 JSON 中的参数由 Jackson 解析。 If the parameter type is 'int' and the user inputs a big number, I have an exception.如果参数类型是 'int' 并且用户输入了一个大数字,我有一个例外。 I restrict doing that on clientside, but want to know, what is the best practice in dealing such type of exceptions?我限制在客户端这样做,但想知道,处理此类异常的最佳做法是什么? Should I bother?我应该打扰吗? Or it's just ok?或者只是没事?

Always include server-side validation始终包括服务器端验证

Since client-side validation can be easily avoided by manually sending a request to an endpoint (in PostMan or using DevTools for example), you are right to encourage validation on both client and server-side.由于可以通过手动向端点发送请求(例如在 PostMan 中或使用 DevTools)轻松避免客户端验证,因此您鼓励在客户端和服务器端进行验证是正确的。 Especially if you want to open up an API publicly, server-side validation is essential.特别是如果你想公开开放一个 API,服务器端验证是必不可少的。 You can not trust every client that interacts with your API.您不能信任与您的 API 交互的每个客户端。 Here are a couple of pointers:这里有一些提示:

Return response status of 422 Unprocessable Entity返回422 Unprocessable Entity响应状态

Assuming you are using HTTP for communication, the appropriate response code to return is 422. 422 represents a validation error and there is a quality explanation here .假设你正在使用HTTP进行通信,适当的响应代码返回是422 422代表一个验证错误,有一个质量的解释在这里 It is more RESTful/HTTP-compliant to return a descriptive status code for different error scenarios.为不同的错误场景返回描述性状态代码更符合 RESTful/HTTP 标准。 For this example, you provide your clients with more information by returning a 422 compared to a 500. You could go even further by returning an error response that describes the field that is invalid.在此示例中,您通过返回 422 而非 500 为您的客户提供更多信息。您可以通过返回描述无效字段的错误响应来更进一步。

Use JAX-RS to map exceptions to responses使用 JAX-RS 将异常映射到响应

JAX-RS is a specification that makes it easy to build RESTful web services in Java. JAX-RS 是一种规范,它使在 Java 中构建 RESTful Web 服务变得容易。 If you have a JAX-RS implementation already wired up in your application, you can define an exception mapper to look for JsonMappingException , check for a cause of NumberFormatException (if you are using boxed Integer ) and return the appropriate response when that case hits.如果您的应用程序中已经有一个 JAX-RS 实现,您可以定义一个异常映射器来查找JsonMappingException ,检查NumberFormatException的原因(如果您使用的是盒装Integer )并在遇到这种情况时返回适当的响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM