微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

@requestbody json 400

@RequestBody JSON 400错误解决办法

@requestbody json 400

在进行Web开发时,常常使用RESTful API来处理数据请求。而当使用@RequestBody注解将请求的JSON数据直接绑定到Java对象时,有时会遇到HTTP 400错误

常见的原因有以下几种:

1. 请求的JSON格式不正确

{
  "name": "John Doe","age": 25,"gender": false
}

2. 请求的JSON数据与Java对象不匹配

public class User {
  private String name;
  private Integer age;
  private String gender;
  
  // getters and setters
}

@RequestMapping(value = "/user",method = RequestMethod.POST)
public ResponseEntity saveUser(@RequestBody User user) {
  // do something
}

3. 请求头Content-Type不正确

headers: {
  'Content-Type': 'application/json'
}

解决办法:

1. 根据请求的JSON格式修改请求体;

2. 根据请求的JSON数据修改Java对象;

3. 确认请求头Content-Type为application/json。

参考代码

@RequestMapping(value = "/user",method = RequestMethod.POST)
public ResponseEntity saveUser(@RequestBody User user) {
  // do something
  return ResponseEntity.ok().build();
}

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
  
  @Override
  protected ResponseEntity handleHttpMessageNotReadable(HttpMessageNotReadableException ex,HttpHeaders headers,HttpStatus status,WebRequest request) {
    String error = "Malformed JSON request";
    return buildresponseEntity(new ApiError(HttpStatus.BAD_REQUEST,error,ex));
  }
  
  private ResponseEntity buildresponseEntity(ApiError apiError) {
    return new ResponseEntity(apiError,apiError.getStatus());
  }
  
  @ExceptionHandler(MethodArgumentTypeMismatchException.class)
  protected ResponseEntity handleMethodArgumentTypeMismatch(MethodArgumentTypeMismatchException ex,WebRequest request) {
    String error = "Method argument type mismatch";
    return buildresponseEntity(new ApiError(HttpStatus.BAD_REQUEST,ex));
  }
  
  @ExceptionHandler(MethodArgumentNotValidException.class)
  protected ResponseEntity handleMethodArgumentNotValid(MethodArgumentNotValidException ex) {
    String error = "Method argument not valid";
    return buildresponseEntity(new ApiError(HttpStatus.BAD_REQUEST,ex));
  }
}

public class ApiError {
  private HttpStatus status;
  private String message;
  private List errors;
  
  public ApiError(HttpStatus status,String message,Throwable ex) {
    this.status = status;
    this.message = message;
    this.errors = Arrays.asList(ex.getMessage());
  }
  
  public HttpStatus getStatus() {
    return status;
  }
  
  public String getMessage() {
    return message;
  }
  
  public List getErrors() {
    return errors;
  }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐