JSONは@NotNull注釈に対応する返された応答を変更する方法

ASharma7:

私ははcustomerIdがRequestBodyに存在しないリターンエラーJSONの簡単なコードを持っています。

VOクラス:

public class OrderVO {

    private int orderId;
    @NotNull(message = "CustomerId Cant be null")
    private Long customerId;
}

コントローラの方法:

@RequestMapping(value="/testOrderbyOrderid", method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE)
public void testOrderJson (@Valid @RequestBody OrderVO orderVO ) {

}

customerIdがRequestBodyに存在しない場合、以下に示すように、現在、JSONの構造が返されます。

{
    "timestamp": "2019-05-14T17:08:01.318+0000",
    "status": 400,
    "error": "Bad Request",
    "errors": [
        {
            "codes": [   ],
            "arguments": [     ],
            "defaultMessage": "CustomerId Cant be null",
            "objectName": "orderVO",
            "field": "customerId",
            "rejectedValue": null,
            "bindingFailure": false,
            "code": "NotNull"
        }
    ],
    "message": "Validation failed for object='orderVO'. Error count: 1",
    "path": "/testOrderbyOrderid"
}

どのように私は下に示したJSON構造に@NotNullで返されるJSON構造上変更することができます。

{
    "timestamp": "2019-05-14T17:08:01.318+0000",
    "status": 400,
    "error": "Bad Request",
    "message": "CustomerId Cant be null"
}

編集 - 私はすでに、コードの見た目が醜いなって、スケールアップとなるフィールドの数が検証= 20のために必要であれば、コードの量がnull&スロー例外をチェックするために必要な、我々はカスタム例外をスローし、ControllerAdviceでそれを扱うことができることを知っているが、考えます。私はこのQnのを掲載している理由です。

エブラヒムPasbani:

お使いのコントローラのアドバイス注釈付きの例外ハンドラに以下のメソッドを追加します。

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(
            MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status,
            WebRequest request) {
        //return your custom error 
        //you can access to field errors using
        //ex.getBindingResult().getFieldErrors()
    }


    @ExceptionHandler(value = { javax.validation.ConstraintViolationException.class })
    protected ResponseEntity<Object> handleConstraintViolation(
            javax.validation.ConstraintViolationException ex) {
        //return your custom error message
    }

    @ExceptionHandler(value = { org.hibernate.exception.ConstraintViolationException.class })
    protected ResponseEntity<Object> handleHibernateConstraintViolation(
            org.hibernate.exception.ConstraintViolationException ex) {
        //return your custom error message
    }

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=204882&siteId=1