如何处理JavaRESTWeb服务中错误JSON数据的错误:Jackson JSON解析器无法识别令牌
这是我的web服务,我在其中接收学生对象中的JSON如何处理JavaRESTWeb服务中错误JSON数据的错误:Jackson JSON解析器无法识别令牌,java,json,rest,jakarta-ee,jackson,Java,Json,Rest,Jakarta Ee,Jackson,这是我的web服务,我在其中接收学生对象中的JSON @PUT @Path("/{stuId}") @Consumes({MediaType.APPLICATION_JSON}) public Response update( @PathParam("stuId") UUID stuUUID , Student updatedStudentInfo) { return updateService.update(stuUUID, updatedSt
@PUT
@Path("/{stuId}")
@Consumes({MediaType.APPLICATION_JSON})
public Response update( @PathParam("stuId") UUID stuUUID , Student updatedStudentInfo) {
return updateService.update(stuUUID, updatedStudentInfo);
}
这是学生班:
public class Student{
private int id;
private String studentName;
private String Address;
@JsonProperty
public int getId() {
return id;
}
@JsonProperty
public void setId(int id) {
this.id = id;
}
@JsonProperty
public String getStudentName() {
return studentName;
}
.
.
.
.
}
它工作正常,但当我通过发送错误的JSON数据对其进行测试时,我无法处理该场景。例如,如果我这样做curl-v'-X PUT-H'Accept:application/json,text/plain,/'-H'My-API版本:1'-H'授权:Basic'-H'内容类型:application/json;charset=utf-8'--数据'{“学生姓名”:“岩石”,“地址”:723868764}'
这是一个错误:
Unrecognized token '723868764': was expecting ('true', 'false' or 'null')
现在,我如何处理这种情况,如果出现了一些错误数据,那么它不应该发回任何错误或异常,除了我想要发送的错误或异常。
编辑1:
下面我们还可以看到Java代码生成的异常
Caused by: com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'sdfsdfdsfdsf': was expecting ('true', 'false' or 'null') at
[Source: org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream@5c6d324d; line: 1, column: 59]
我找到了两种解决方案:
解决方案1:例外情况(泽西岛)
请求的事件侦听器也可用
RequestEventListener
,它提供了onEvent(RequestEvent)
方法。
我更喜欢使用解决方案#2为什么您得到
true
,false或null,它不是一个布尔对象您可以尝试捕获该异常并在其中定义您自己的自定义消息:catch(JSONException e){//add custome ex message here e.getMessage()}
还将抛出无法识别的令牌,因为您已将地址声明为字符串,并且可能试图将其设置为数字而不是字符串,请将其括在双引号中,这样可能会使错误消失@coolgirl是的,我故意传递数字而不是字符串,这是我的问题,如果我发送了一些错误的JSON数据,我该如何处理它?其次,我在代码中的何处可以使用此TRY-CATCH,因为此异常是在方法的签名级别生成的,所以编译器甚至不在方法内部。我认为TRY-CATCH处理应该在您的服务类中完成。@CarlosLaspina-与对coolgirl
的解释相同,问题的目的是修复错误处理。OP非常清楚数据是无效的。
@Provider
public class ClientExceptionMapper implements ExceptionMapper<Throwable>
{
@Override
public Response toResponse(Throwable ex)
{
return Response
.status(Response.Status.BAD_REQUEST)
.build();
}
}
<servlet>
<servlet-name>my-servlet</servlet-name>
<servlet-class>
org.glassfish.jersey.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>jersey.config.server.provider.packages</param-name>
<param-value>
com.myrootpackgae.ws;com.anotherPackage.errorHandling;
</param-value>
</init-param>
<init-param>
<param-name>jersey.config.server.provider.scanning.recursive</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
public class MyRestAppResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
// Remove StackTrace from all exceptions
Object entity = responseContext.getEntity();
if (entity instanceof Throwable) {
responseContext.setEntity(null);
responseContext.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
}
// TF-246 Prevent caching for privacy reasons
responseContext.getHeaders().add("Cache-Control", "no-cache, no-store, must-revalidate");
responseContext.getHeaders().add("Pragma", "no-cache");
responseContext.getHeaders().add("Expires", "Thu, 01 Jan 1970 01:00:00 CET");
// TF-752 Enable CORS for WkWebView
responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
}
}