java.lang.ClassCastException: java.util.LinkedHashMap 不能 cast to com.testing.models.Account

2022-08-31 09:59:55

我得到以下错误:

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

这个问题来自杰克逊。当它没有足够的信息来反序列化到哪个类时,它使用 。LinkedHashMap

由于您没有通知 Jackson 您的 的元素类型,因此它不知道您要反序列化为 an of s。因此,它回退到默认值。ArrayListArrayListAccount

相反,您可能可以使用 ,然后以比放心所允许的更丰富的方式处理 。像这样: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);

答案 2

请尝试以下操作:

POJO pojo = mapper.convertValue(singleObject, POJO.class);

艺术

List<POJO> pojos = mapper.convertValue(
    listOfObjects,
    new TypeReference<List<POJO>>() { });

有关详细信息,请参阅LinkedHashMap的转换


推荐