当前位置: 首页 > 知识库问答 >
问题:

ClassCastException:java.util.LinkedHashMap不能强制转换为com.testing.models.Account

叶鸿振
2023-03-14
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)有什么原因吗?

共有1个答案

冯奇思
2023-03-14

问题来自杰克逊。当它没有足够的信息说明要反序列化为什么类时,它就使用LinkedHashMap

因为您没有通知Jackson您的ArrayList元素类型,所以它不知道您想要反序列化为ArrayList帐户的ArrayList。所以它回到默认值。

相反,您可能可以使用作为(jsonnode.class),然后以比REST保证允许的更丰富的方式处理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);
 类似资料: