gpt4 book ai didi

java.lang.ClassCastException : java. util.LinkedHashMap 无法转换为 com.testing.models.Account

转载 作者:IT老高 更新时间:2023-10-28 20:24:16 31 4
gpt4 key购买 nike

我遇到以下错误:

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

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

相反,您可能可以使用 as(JsonNode.class),然后以比放心允许的更丰富的方式处理 ObjectMapper。像这样的:

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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28821715/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com