ObjectMapper无法反序列化 - 无法反序列化START_ARRAY令牌中的....的实例

时间:2014-10-10 15:14:17

标签: java json jackson deserialization

我有一个像这样的json:

{
  "games": [
      {
        "id": "mhhlhlmlezgwniokgawxloi7mi",
        "from": "425364_456@localhost",
        "to": "788295_456@localhost",
        "token": "xqastwxo5zghlgjcapmq5tirae",
        "desc": "6CeF9/YEFAiUPgLaohbWt9pC7rt9PJlKE6TG6NkA4hE=",
        "timestamp": 1412806372232
      },
      {
        "id": "62jzlm64zjghna723grfyb6y64",
        "from": "425364_456@localhost",
        "to": "788295_456@localhost",
        "token": "xqastwxo5zghlgjcapmq5tirae",
        "desc": "Z/ww2XroGoIG5hrgiWsU1P8YHrv4SxiYHHoojzt9tdc=",
        "timestamp": 1412806373651
      }
    ]
}

我尝试将其反序列化为ObjectMapper的对象。基本上你可以看到,它是一个游戏列表。

我有这样的课程:

@JsonRootName(value="games")
public class GameJson{
    private List<Game> games;
// getters and setters

}

游戏课程在这里:

public class Game{
    private String id;

    private String from;

    private String to;

    private String token;

    private String desc;

    private Instant timestamp;

    // getters and setters
}

在我的代码中,ObjectMapper正在执行此操作:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);

GameJson json = mapper.readValue(
                       new FileInputStream(gamesFile), GameJson.class);

然后我收到此错误:

无法从com.games.collection.GameJson令牌中反序列化START_ARRAY的实例

我正在尝试不同的方法来做到这一点,但没有运气就出来了。有人可以帮忙吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

摆脱

@JsonRootName(value="games")

该注释将带注释的类型标识为映射到名为"games"的JSON键的JSON对象的目标。在您的情况下,这是一个JSON数组。无法将数组反序列化到GameJson类中。

As you stated in the comments,您还需要删除启用@JsonRootName的配置。

mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
相关问题