我要使用此Response对象返回错误列表:
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;
}
}
我使用以下代码生成错误:
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()));
}
我想返回这样的列表:
response: {
errors: [
field_name: message,
second_name: second_message
]
}
您知道如何修改代码吗?也许我需要添加构造函数?
答案 0 :(得分:1)
response: {
errors: [
field_name: message,
second_name: second_message
]
}
您需要使用以下类对上述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;
}
}
您可以将响应构造为:
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));