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

查看:31
本文介绍了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)?

推荐答案

问题来自 Jackson.当它没有关于要反序列化为哪个类的足够信息时,它使用 LinkedHashMap.

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

由于您没有将 ArrayList 的元素类型通知 Jackson,因此它不知道您要反序列化为 Account 的 ArrayList s.所以它回退到默认值.

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.

相反,您可能可以使用 as(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.convertValue(
    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天全站免登陆