I'm getting below error:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.testing.models.Account
with below code
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);
Is there a reason why I cannot do get(0)
?
The issue's coming from Jackson. When it doesn't have enough information on what class to deserialize to, it uses
LinkedHashMap
.Since you're not informing Jackson of the element type of your
ArrayList
, it doesn't know that you want to deserialize into anArrayList
ofAccount
s. So it falls back to the default.Instead, you could probably use
as(JsonNode.class)
, and then deal with theObjectMapper
in a richer manner than rest-assured allows. Something like this:The way I could mitigate the JSON Array to collection of LinkedHashMap objects problem was by using
CollectionType
rather than aTypeReference
. This is what I did and worked:Using the
TypeReference
, I was still getting an ArrayList of LinkedHashMaps, i.e. does not work:Try the following:
or:
See conversion of LinkedHashMap for more information.
I had a similar exception (but different problem) -
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to org.bson.Document
, and fortunately it's solved easier:Instead of
which gives error on second line, One can use
I have this method for deserializing an XML and converting the type:
and this is the call: