Skip to content

Instantly share code, notes, and snippets.

@gitjs77
Last active March 3, 2018 10:25
Show Gist options
  • Save gitjs77/c06563ee7415c02076109983e7efa953 to your computer and use it in GitHub Desktop.
Save gitjs77/c06563ee7415c02076109983e7efa953 to your computer and use it in GitHub Desktop.
/**
* Gets List<T> from Mvc result Json path.
*
* @param mvcResult - MvcResult from resource test
* @param listJsonPath - list Json path
* @param <T> - types of elements of the list
* @return List<T>
*/
public <T> List<T> getListFromMvcResultJsonPath(final MvcResult mvcResult, final JsonPath listJsonPath) {
try {
return JsonPath.read(mvcResult.getResponse().getContentAsString(), "$." + listJsonPath + "[*]");
// If first variant trow UnsupportedEncodingException we use alternative way for parse List<T>
} catch (UnsupportedEncodingException ex) {
final Configuration jsonPathConfigurationForGetListsFromJson = Configuration
.builder()
.jsonProvider(new JacksonJsonProvider())
.mappingProvider(new JacksonMappingProvider())
.build();
try {
return JsonPath.using(jsonPathConfigurationForGetListsFromJson) // Switch configuration to custom
.parse(mvcResult.getResponse().getContentAsString())// JSON
.read("$." + listJsonPath, new TypeRef<List<T>>() {
});
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
}
return new ArrayList<>();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment