【发布时间】:2015-11-06 13:09:26
【问题描述】:
我正在使用 Spring MVC 制作游戏(尝试...),例如 Risk for university。我正在使用 JPA,我需要将游戏状态(玩家轮到,国家单位等)保存在一个用 JSON 编码的字符串字段中,这就是让我发疯的原因。 首先,我使用其他信息(id、用户所有者、状态...)创建游戏,当它第一次启动时,我想生成 JSON 并将其设置为实体并保存它。我尝试使用 entityManager.merge(game) 但是当我查看数据库时,JSON 字段为空。我试图制作 namedquery 和 nativequery,但在 JSON 字符串中有 " 它是一团糟。 有什么想法为什么不通过合并保存? 代码是这样的:
HomeController.class
public String getGame(@PathVariable("idGame") long idGame,
Model model) throws IOException {
Game g = GameDao.getGame(idGame);
if (g.getJson == null) {
g.initializeGame(); // it sets the json attribute
GameDao.update(entityManager, g);
}
}
GameDAO.class
@Transactional
public static Game update(EntityManager entityManager, Game g) {
try {
entityManager.merge(g); // if I debug here g has the json attribute setted
return entityManager.find(Game.class, g.getId()); // the game object that's returned hasn't the json field setted
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
这是 repo https://github.com/alvardsoler/reinvasion,但它是西班牙语中最多的。九月份的考试,我没有太多的时间,所以我想先把它做的很粗略,然后如果我有时间,我会做得很好。如果我无法将 JSON 信息保存在数据库中,我会将其保存在服务器中的一个文件中,其中包含游戏 ID 或类似的东西。
【问题讨论】:
-
已经尝试过 GSON 库?我们在类似的情况下使用它并且效果很好:github.com/google/gson
-
@Phiwa 以什么方式?我用它来创建 JSON 字符串 Gson gson = new Gson(); this.json = gson.toJson(jp, JuegoPartida.class); (在 initializeGame() 中)。
标签: java json spring-mvc jpa