【问题标题】:How to turn off deserialization for enum如何关闭枚举的反序列化
【发布时间】:2020-08-25 20:51:29
【问题描述】:

我想关闭具体枚举的反序列化。有可能吗?

运动模型类:

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;
    }
}

【问题讨论】:

  • 你能解释一下你所说的“关闭反序列化”是什么行为吗?

标签: java enums jackson


【解决方案1】:

要关闭(反)序列化,您可以将@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 了解更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-31
    • 2015-07-26
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多