Spring ClassCastException?



java.lang.ClassCastException:类java.lang.Double不能强制转换为类java.lang.Integer(java.lang.Ddouble和java.lang.Interger在加载程序'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数据库

这个异常让我很困惑。

这就是我解决这个问题的方法;首先,我没有从json中获取List,而是尝试获取int[],使用它并转换为列表

相关内容

  • 没有找到相关文章

最新更新