如何使用asserj断言嵌套json的值?

问题描述

我正在尝试使用 assertJ 从 JSON 映射对象打印和断言 addressLine1postcode 值,但在断言时遇到问题。

{
  "Region": {
    "Test": {
      "address": {
        "addressLine1": "addressLine1","addressLine2": "addressLine2","otherDetails": {
          "postcode": "LS1 4HR","country": "United Kingdom"
        }
      }
    }
  }
}

我已将 jabove json 转换为 Map jsonAsMap 并在下面尝试:

assertthat(jsonAsMap)
                .isNotNull()
                .isNotEmpty()
                .hasEntrySatisfying("Region",Region -> assertthat(Region).hasFieldOrProperty("Test").hasFieldOrProperty("address") )
                   .containsEntry("addressLine1","addressLine1");

解决方法

我建议将 https://github.com/lukas-krecan/JsonUnit 用于 JSON 断言(或任何其他 JSON 断言库),您将获得比不了解 JSON 的 AssertJ 更好的功能。