【发布时间】:2017-12-03 01:21:14
【问题描述】:
我有一个非常基本的 Spring Boot 应用程序,其中包含 .-data-jpa、.-data-rest 和 .-web 依赖项。
在我的模型中有一个实体Game,它包含一个整数属性homeGameSwitch。
当我通过 REST 调用获取资源时,会出现以下异常:
.w.s.m.s.DefaultHandlerExceptionResolver : 无法写入 HTTP 信息: org.springframework.http.converter.HttpMessageNotWritableException: 无法写入 JSON:java.lang.Integer 无法转换为 java.lang.String;嵌套异常是 com.fasterxml.jackson.databind.JsonMappingException: java.lang.Integer 不能转换为 java.lang.String (通过引用链: org.springframework.data.rest.webmvc.json.PersistentEntityJackson2Module$PersistentEntityResourceSerializer$1["content"]->com.coli.stripebackend.model.Game["homeGameSwitch"])
Jackson 不能处理整数,我觉得很奇怪。 我能做些什么来防止这个错误吗?
实体:
@Entity
public class Game {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private Integer homeGameSwitch;
public Integer getHomeGameSwitch() {
return homeGameSwitch;
}
DAO:
@Repository("gameDao")
public interface GameDao extends JpaRepository<Game, Integer> {}
服务:
@Service("gameService")
public class GameServiceImpl implements GameService {
@Autowired
private GameDao gameDao;
@Override
public Game retrieveGameById(Integer id) throws Exception {
Optional<Game> optionalGame = gameDao.findById(id);
return optionalGame.get();
}
调用localhost:8080/game/7时出现错误
【问题讨论】:
-
向我们展示您的实体(或至少重现问题所需的最少代码)以及您正在做什么来获得此异常。另请阅读 minimal reproducible example 和 What topics can I ask about here?(更准确地说是第 (1) 点)。
-
@Coli,因为 -1 不是我写的,也许可以告诉任何人
-
您仍然缺少一些信息。您首先说您使用的是 spring-data-rest,但您没有使用任何 REST 存储库,那么当您调用
/game/7时,所提供的代码到底在哪里? -
我还在学习,但是在使用 spring-data-rest 时遵循this tutorial 不需要添加任何代码来拥有 REST API。从数据库检索后出现错误的事实证明 REST API 正在使用此 URL。
标签: json spring spring-boot jackson