我得到下面的错误:
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)
有什么原因吗?
发布于 2015-03-03 08:16:02
问题出在杰克逊身上。当它没有足够的信息来反序列化到哪个类时,它就会使用LinkedHashMap
。
因为您没有通知Jackson您的ArrayList
的元素类型,所以它不知道您想要反序列化为Account
s的ArrayList
,所以它回到了缺省值。
相反,您可能会使用as(JsonNode.class)
,然后以比rest-assured允许的更丰富的方式处理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);
发布于 2016-07-27 14:40:05
尝试以下操作:
POJO pojo = mapper.convertValue(singleObject, POJO.class);
或者:
List<POJO> pojos = mapper.convertValue(
listOfObjects,
new TypeReference<List<POJO>>() { });
有关详细信息,请参阅conversion of LinkedHashMap。
发布于 2016-06-06 20:02:23
我有一个类似的异常(但问题不同)- java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.bson.Document
,幸运的是它更容易解决:
而不是
List<Document> docs = obj.get("documents");
Document doc = docs.get(0)
它在第二行给出了错误,可以使用
List<Document> docs = obj.get("documents");
Document doc = new Document(docs.get(0));
https://stackoverflow.com/questions/28821715
复制相似问题