java.lang.ClassCastException:java.util.LinkedHashMap无法强制转换为com.testing.models.Account [英] java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

查看:114
本文介绍了java.lang.ClassCastException:java.util.LinkedHashMap无法强制转换为com.testing.models.Account的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account

以下代码

final int expectedId = 1;

Test newTest = create();

int expectedResponseCode = Response.SC_OK;

ArrayList<Account> account = given().when().expect().statusCode(expectedResponseCode)
    .get("accounts/" + newTest.id() + "/users")
    .as(ArrayList.class);
assertThat(account.get(0).getId()).isEqualTo(expectedId);

我有什么理由不能做 get(0)

推荐答案

这个问题来自杰克逊。如果没有关于要反序列化的类的足够信息,它使用 LinkedHashMap

The issue's coming from Jackson. When it doesn't have enough information on what class to deserialize to, it uses LinkedHashMap.

由于你没有通知杰克逊你的 ArrayList 的元素类型,它不知道你想要反序列化为帐户 ArrayList 。所以它回退到默认值。

Since you're not informing Jackson of the element type of your ArrayList, it doesn't know that you want to deserialize into an ArrayList of Accounts. So it falls back to the default.

相反,您可以使用作为(JsonNode.class),并且然后以比确定允许更丰富的方式处理 ObjectMapper 。这样的事情:

Instead, you could probably use as(JsonNode.class), and then deal with the ObjectMapper in a richer manner than rest-assured allows. Something like this:

ObjectMapper mapper = new ObjectMapper();

JsonNode accounts = given().when().expect().statusCode(expectedResponseCode)
    .get("accounts/" + newClub.getOwner().getCustId() + "/clubs")
    .as(JsonNode.class);


//Jackson's use of generics here are completely unsafe, but that's another issue
List<Account> accountList = mapper.readValue(
    mapper.treeAsTokens(accounts), 
    new TypeReference<List<Account>>(){}
);

assertThat(accountList.get(0).getId()).isEqualTo(expectedId);

这篇关于java.lang.ClassCastException:java.util.LinkedHashMap无法强制转换为com.testing.models.Account的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆