问题
I wan to return a list of errors using this Response object:
public class StringResponseDTO {
private String response;
public StringResponseDTO(String response) {
super();
this.response = response;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}
}
I use this code to generate errors:
List<FieldError> errors = result.getFieldErrors();
for (FieldError error : errors ) {
System.out.println ("Validation error in field: " + error.getObjectName()
+ "! Validation error message: " + error.getDefaultMessage()
+ "! Rejected value:" + error.getRejectedValue());
return ResponseEntity.ok(new StringResponseDTO(error.getField() + " " + error.getDefaultMessage()));
}
I want to return a list like this:
response: {
errors: [
field_name: message,
second_name: second_message
]
}
Do you know how I can modify the code? Probably I need add constructor?
回答1:
response: {
errors: [
field_name: message,
second_name: second_message
]
}
You need to use the following classes to model the above json:
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
@JsonTypeName("response")
class StringResponseDTO {
private List<String> errors;
public StringResponseDTO(final List<String> errors) {
this.errors = errors;
}
public List<String> getErrors() {
return errors;
}
public void setErrors(final List<String> errors) {
this.errors = errors;
}
}
You can construct the response as:
List<String> errorsList = new ArrayList<>();
List<FieldError> errors = result.getFieldErrors();
for (FieldError error : errors ) {
System.out.println ("Validation error in field: " + error.getObjectName()
+ "! Validation error message: " + error.getDefaultMessage()
+ "! Rejected value:" + error.getRejectedValue());
errorsList.add(error.getField() + " " + error.getDefaultMessage());
}
return ResponseEntity.badRequest().body(new StringResponseDTO(errorsList));
来源:https://stackoverflow.com/questions/55445649/return-list-of-errors