【问题标题】:Jackson tries to cast Integer to String杰克逊试图将整数转换为字符串
【发布时间】: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 exampleWhat 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


【解决方案1】:

问题与 Spring Boot 的版本有关。我使用的是 2.0.0.M2 版本,其中似乎存在错误。 我在使用 1.5.4.RELEASE 版本时没有问题。

【讨论】:

    【解决方案2】:

    这是对未来来这里的读者的一个警告:触发这个异常的方法有很多:一些类似的收集在Jackson serialization exception when trying to serialize LocalDateTime

    看来我只是遇到了另一种获得完全相同异常的方法:有一个这样的类:

    class Foo extends HashMap<String, String> {
      public long bar;
    }
    

    并尝试对其进行序列化。

    【讨论】:

      猜你喜欢
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      • 2012-11-15
      相关资源
      最近更新 更多