Try JCV online

A simple assertion with default validators:



import com.ekino.oss.jcv.assertion.assertj.JsonCompareAssert.Companion.assertThatJson
import org.junit.Test

class Example1Test {

    @Test
    fun `should validate actual JSON against the expected one`() {

//sampleStart
        val actualJson = """
            {
              "field_1": "some value",
              "field_2": "3716a0cf-850e-46c3-bd97-ac1f34437c43",
              "date": "2011-12-03T10:15:30Z",
              "other_fields": [{
                "id": "2",
                "link": "https://another.url.com/my-base-path/query?param1=true"
              }, {
                "id": "1",
                "link": "https://some.url.com"
              }]
            }
            """.trimIndent()

        val expectedJson = """
                {
                  "field_1": "some value",
                  "field_2": "{#uuid#}",
                  "date": "{#date_time_format:iso_instant#}",
                  "other_fields": [{
                    "id": "1",
                    "link": "{#url#}"
                  }, {
                    "id": "2",
                    "link": "{#url_ending:query?param1=true#}"
                  }]
                }
                """.trimIndent()

        assertThatJson(actualJson).isValidAgainst(expectedJson)
//sampleEnd
    }
}


JCV libraries available: jcv-assertj:1.5.0 and jcv-hamcrest:1.5.0

Try with your custom validator:



import com.ekino.oss.jcv.assertion.assertj.JsonCompareAssert.Companion.assertThatJson
import com.ekino.oss.jcv.core.JsonValueComparator
import com.ekino.oss.jcv.core.validator.Validators.defaultValidators
import com.ekino.oss.jcv.core.validator.validators
import org.junit.Test
import org.skyscreamer.jsonassert.ValueMatcherException

class Example2Test {

//sampleStart
    @Test
    fun `should validate json content with custom validator`() {

        assertThatJson(
            """
            {
              "id": "fda7a233-99b9-4756-8ecc-826a1c5a9bf5",
              "reference": "REF_0123456789"
            }
            """.trimIndent()
        )
            .using(validators {
                +defaultValidators()
                +templatedValidator("my_ref", MyRefComparator())
            })
            .isValidAgainst(
                """
                {
                  "id": "{#uuid#}",
                  "reference": "{#my_ref#}"
                }
                """.trimIndent()
            )
    }

    private class MyRefComparator : JsonValueComparator<String> {

        override fun hasCorrectValue(actual: String?, expected: String?): Boolean {
            if (actual != null && actual.startsWith("REF_") && actual.length == 14) {
                return true
            }
            throw ValueMatcherException("Invalid reference format", expected, actual)
        }
    }
//sampleEnd
}


JCV libraries available: jcv-assertj:1.5.0 and jcv-hamcrest:1.5.0