0

If you have a JSON Object (in Java) with multiple nested fields, how do you assert that a specific field is not present?

e.g. For the following object below, how would you assert that field C does/does not exist:

{
"A": {
       "B": {
           "C": "field exists"
       }
     }
}
kaido
  • 321
  • 1
  • 5
  • 15

2 Answers2

0

this is an idea. you can bind the json to a java object using any libraries such as jackson. the object class you could add bean validation annotations like @NonNull etc . then you can obtain a bean validator object and call validate on the java object. this will give you a set of errors .

https://docs.oracle.com/javaee/6/tutorial/doc/gircz.html

also there are 2 libraries that implements jsr 303

Is there an implementation of JSR-303 (bean validation) available?

a small tutorial is availabe here https://www.baeldung.com/javax-validation

0

For unit testing with java and json I use the hamcrest library and one of it extension json-path-assert.

This let me assert using json-path expressions.

Assert that C does exist

assertThat(yourJsonString, hasJsonPath("$.*.*.C"));

Assert than C doesn't exist

assertThat(yourJsonString, hasNoJsonPath("$.*.*.C"));
theBittor
  • 786
  • 1
  • 11
  • 20