Skip to content

Commit

Permalink
Validate required properties on empty object, re #48
Browse files Browse the repository at this point in the history
  • Loading branch information
safris committed Oct 6, 2023
1 parent 3cf765d commit 57859d1
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
8 changes: 7 additions & 1 deletion binding/src/main/java/org/jsonx/ObjectCodec.java
Original file line number Diff line number Diff line change
Expand Up @@ -146,10 +146,16 @@ else if (codec instanceof ArrayCodec) {
}

// If this {...} contained properties, ensure that no properties are missing (i.e. use=required).
if (unvisitedCodecs != null)
if (unvisitedCodecs != null) {
for (final Codec unvisitedCodec : unvisitedCodecs) // [A]
if (unvisitedCodec != null && unvisitedCodec.use == Use.REQUIRED)
return abort(Error.PROPERTY_REQUIRED(unvisitedCodec.name, null), reader, index);
}
else {
for (final Codec unvisitedCodec : propertyToCodec.allCodecs) // [A]
if (unvisitedCodec.use == Use.REQUIRED)
return abort(Error.PROPERTY_REQUIRED(unvisitedCodec.name, null), reader, index);
}

return object;
}
Expand Down
14 changes: 13 additions & 1 deletion binding/src/test/java/org/jsonx/LibraryTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -105,9 +105,21 @@ public void testAddressDecodeException() throws IOException {
try {
final String json = "{\"street\":\"Sukhumvit Soi 13\",\"city\":\"Salt Lake City\",\"postalCode\":\"19207\",\"locality\":\"Minnesota\",\"country\":\"Thailand\"}";
JxDecoder.VALIDATING.parseObject(json, Address.class);
fail("Expected DecodeException due to missing \"number\"");
fail("Expected DecodeException");
}
catch (final DecodeException e) {
assertEquals("Property \"number\" is required: null", e.getMessage());
}
}

@Test
public void testAddressDecodeExceptionEmpty() throws IOException {
try {
JxDecoder.VALIDATING.parseObject("{}", Address.class);
fail("Expected DecodeException");
}
catch (final DecodeException e) {
assertEquals("Property \"number\" is required: null", e.getMessage());
}
}

Expand Down

0 comments on commit 57859d1

Please sign in to comment.