2

I'm fairly new to Spring framework and I'm trying to learn by developing an example project

Maybe this is a fool question but I cannot find any help at all.

My controller is responding to requests with an escaped string instead of json representation of the object, when the validation rules do not pass. Im using bean validators, and Gson to generate an error json representation of the errors.

My controller is responding with:

"{\"firstName\":\"firstName required\",\"lastName\":\"lastName required\",\"password\":\"password required\",\"matchingPassword\":\"matchingPassword required\",\"email\":\"email required\"}"

But in console, Gson prints a correct json representation

{"firstName":"firstName required","lastName":"lastName required","password":"password required","matchingPassword":"matchingPassword required","email":"email required"}

Here is my controller:

    @RequestMapping(value = "/user/registration", method = RequestMethod.POST, headers = "Accept=application/json", produces = {"application/json"})
public ResponseEntity<String> registerUserAccount(@Valid @RequestBody UserDTO accountDto) {
    LOGGER.debug("Registering user account with information: {}", accountDto);
    User registered = userService.registerNewUserAccount(accountDto);
    return new ResponseEntity<>("Success", HttpStatus.OK);
}

@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity handleValidationExceptions(MethodArgumentNotValidException ex) {
    LOGGER.debug("MethodArgumentNotValidException called");
    Map<String, String> errors = new HashMap<>();
    ex.getBindingResult().getAllErrors().forEach((error) -> {
        String fieldName = ((FieldError) error).getField();
        String errorMessage = error.getDefaultMessage();
        errors.put(fieldName, errorMessage);
    });
    Gson gson = new Gson();
    LOGGER.debug(gson.toJson(errors));
    return ResponseEntity.badRequest().contentType(MediaType.APPLICATION_JSON).body(gson.toJson(errors));
}

I've tried lots of possible solutions but none of them work, always returns escaped string representation of the object.

Any help would be appreciated, I've lost lots of time trying to solve this, and I feel like this is something fool, but I cannot move forward because I cannot even complete my first controller

here is the git of the project, if needed

1 Answers1

2

Solved.

As I suspected, it was a fool error on my part,

ResponseEntity was taking as String as T, so, when passed to response, String was processed by StringHttpMessageConverter, which escapes the string.

When returning Objects as T with ResponseEntity, we should give an object to be represented or a wrapper class for the data, or escape the string.

Another workaround is to turnoff the StringHttpMessageConverter, which can be done in WebMvcConfiguration, but its not recommended unless under certain circunstances.

Further help can be found in: https://stackoverflow.com/a/37906098/12771022