Search code examples
jsonspringjunitjsonpathassertj

What is the best way to check all JSON properties values type?


I'm trying to check in my integration test if all of values from some specific property has the same type. I was trying to do it along with jsonPath and JsonPathResultMatchers but without success. Finally in I did something like this :

MvcResult result = mockMvc.perform(get("/weather/" + existingCity))
                 .andExpect(MockMvcResultMatchers.status().isOk())
                 .andReturn();


String responseContent = result.getResponse().getContentAsString();
TypeRef<List<Object>> typeRef = new TypeRef<List<Object>>() {
};

List<Object> humidities = JsonPath.using(configuration).parse(responseContent).read("$.*.humidity", typeRef);
Assertions.assertThat(humidities.stream().allMatch(humidity -> humidity instanceof Integer)).isTrue();

But I wonder if exist some clearer way to do this, can the same result be achieved with JSONPath ? Or AssertJ has some method to find it without usage stream code


Solution

  • I personnaly would rather validate it against a JSON schema. There are Java validator implementations that could help you