[英]How to turn off deserialization for enum
我想關閉具體枚舉的反序列化。 是否可以?
運動模型類:
package main.exercise;
import lombok.*;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Entity
@Builder
public class Exercise {
@Id
@GeneratedValue
private int id;
@NonNull
private String name;
@NonNull
private ExerciseType exerciseType;
private double caloriesBurned;
private String exerciseDescription;
}
我在控制器中得到了方法:
@PostMapping("/addExercise")
public List<String> addExercise(@RequestBody Exercise exercise) {
return exerciseCrudActivitiesService.addExercise(exercise);
}
這需要運動體,如果運動類型錯誤,我在 POST http 請求時出錯:
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `main.exercise.ExerciseType` from String "CARdDIO": not one of the values accepted for Enum class: [CARDIO, WEIGHTLIFTING]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `main.exercise.ExerciseType` from String "CARdDIO": not one of the values accepted for Enum class: [CARDIO, WEIGHTLIFTING]
at [Source: (PushbackInputStream); line: 4, column: 25] (through reference chain: main.exercise.Exercise["exerciseType"])]
關鍵是我得到了驗證器,它驗證枚舉類型是對還是錯,並將字符串返回到所有驗證器的錯誤列表。 不幸的是,由於錯誤,無法訪問此代碼。
public List<String> addExercise(Exercise exercise) {
ExerciseValidator validator = new ExerciseValidator();
List<String> messages = validator.validate(exercise);
if (messages.isEmpty()) {
exerciseRepository.save(exercise);
}
return messages;
}
驗證器
package main.exercise.validator.attributesvalidators;
import main.exercise.Exercise;
import main.exercise.ExerciseType;
import main.exercise.validator.ExerciseAttributesValidator;
import java.util.InputMismatchException;
public class ExerciseTypeValidator implements ExerciseAttributesValidator {
@Override
public String validate(Exercise exercise) {
if (exercise.getExerciseType() == null) {
return "You didn't put exercise type!";
}
try {
ExerciseType.forName(exercise.getExerciseType().name());
} catch (InputMismatchException e) {
return "Wrong exercise type!";
}
return null;
}
}
要關閉(反)序列化,您可以將@JsonIgnore
添加到exerciseType
字段。 但是,我認為這無論如何都不會幫助您。
如果忽略序列化,該字段將始終為null
,這不是預期的行為。
您的驗證器為時已晚。 注意:validate 方法以一個Exercise
對象作為參數。 在創建此對象的過程中已經發生了問題。 當你到達這一點時,行ExerciseType.forName(exercise.getExerciseType().name());
get 被執行,它永遠不會拋出異常,因為getExerciseType()
已經是一個有效的枚舉。
您可以使用 Spring @ControllerAdvice
為該錯誤類型注冊您自己的異常處理程序,而不是這個自定義驗證器。
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import com.fasterxml.jackson.databind.exc.InvalidFormatException
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(InvalidFormatException.class)
public ResponseEntity<?> badFormatException(InvalidFormatException ex, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.BAD_REQUEST);
}
}
有關更多詳細信息,請參見例如https://www.springboottutorial.com/spring-boot-exception-handling-for-rest-services 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.