Spring ClassCastException?
Posted
技术标签:
【中文标题】Spring ClassCastException?【英文标题】:Spring ClassCastException? 【发布时间】:2021-07-31 04:15:02 【问题描述】:java.lang.ClassCastException:类 java.lang.Double 不能转换为类 java.lang.Integer(java.lang.Double 和 java.lang.Integer 位于加载器“bootstrap”的模块 java.base 中)
//using lombok
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
public class Quiz
@Id
@Column
int id;
@Column
String title;
@Column
String text;
@ElementCollection
@Column
List<String> options;
@ElementCollection
@Column
List<Integer> answer = new ArrayList<>(); //this is obviously a list of Integers
@Service
public class QuizService
@Autowired
Repo repo;
public List<Quiz> getAllQuiz()
List<Quiz> quizList = new ArrayList<>();
repo.findAll().forEach(quiz -> quizList.add(quiz));
return quizList;
public void saveNewQuiz(Quiz quiz)
repo.save(quiz); //error occurred here
public void deleteQuiz(Quiz quiz)
repo.delete(quiz);
import engine.Quiz;
import org.springframework.data.repository.CrudRepository;
public interface Repo extends CrudRepository<Quiz, Integer>
@PostMapping(value = "/api/quizzes", produces = "application/json")
@ResponseBody
public String newQuiz(@RequestBody String json)
Import();
Gson gson = new Gson();
JsonObject jObj = new JsonObject();
try
jObj = new JsonParser().parse(json).getAsJsonObject();
catch(Exception e)
throw new ResponseStatusException(HttpStatus.BAD_REQUEST);
//test out the json
requestHandler(jObj);
Quiz quiz = new Quiz();
int id = idGenerator();
quiz.setId(id);
quiz.setTitle(jObj.get("title").getAsString());
quiz.setText(jObj.get("text").getAsString());
quiz.setOptions(gson.fromJson(jObj.get("options").getAsJsonArray(), List.class));
try
List<Integer> list = gson.fromJson(jObj.get("answer").getAsJsonArray(), List.class);
quiz.setAnswer(list);
catch(Exception ignored)
quizzes.add(quiz);
service.saveNewQuiz(quiz); //error occured here
return getQuiz(id);
我什至都没碰过 Double,怎么会有从 Double 到 Integer 的类转换异常?
我不能做的事:
我无法将类型从 Integer 更改为 Double 因为项目 需要整数才能起作用。 我无法更改数据库,因为项目需要 h2 数据库这个异常让我感到困惑。
【问题讨论】:
我确定您知道调试器是什么......您是否尝试过验证传入的数据?您是否验证了该数据的转换?您是否已验证数据已正确传递到存储库? @Tom 打印出语句的正常调试过程在spring中不起作用,我试过但没有任何东西打印到控制台 【参考方案1】:这就是我解决这个问题的方法; 首先,我没有从 json 获取列表,而是尝试获取 int[],使用它并转换为列表
【讨论】:
以上是关于Spring ClassCastException?的主要内容,如果未能解决你的问题,请参考以下文章
json中的Spring Data Redis缓存抛出ClassCastException
Spring批量集成:java.lang.ClassCastException:org.springframework.integration.file.FileReadingMessageSourc
Spring-Integration:将 DirectChannel 更改为 ExecutorChannel 结果为 ClassCastException
Spring OAuth2 自定义身份验证管理器 ClassCastException
在调用处理程序之前使用 Tomcat 8 和 Spring 4 ClassCastException 的 websockets
Spring-Data-Redis--解决java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to xxx