检查所有 JSON 属性值类型的最佳方法是什么?

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

我正在尝试检查我的集成测试是否来自某个特定 属性 的所有值都具有相同的类型。我试图与 jsonPath 和 JsonPathResultMatchers 一起做,但没有成功。最后我做了这样的事情:

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();

但我想知道是否存在更清晰的方法来做到这一点,使用 JSONPath 可以实现相同的结果吗?或者 AssertJ 有一些方法可以在不使用流代码的情况下找到它

我个人更愿意根据可以帮助您的 JSON schema. There are Java validator implementations 验证它

只是回答 AssertJ 部分:Stream 断言提供了一些注意事项,因为测试中的 Stream 被转换为 List 以便能够执行多个断言(否则你不能,因为 Stream 只能被消费一次)。

Javadoc:assertThat(BaseStream)

示例:

assertThat(DoubleStream.of(1, 2, 3)).isNotNull()
                                    .contains(1.0, 2.0, 3.0)
                                    .allMatch(Double::isFinite);

我已经愉快地使用https://github.com/lukas-krecan/JsonUnit来查看JSON,你可以试一试,看看你是否喜欢