Skip to content

Commit 39cc79b

Browse files
authored
Prevent from throwing an exception when setting default values (#561)
- this happens when an expected object has a different type i.e. a string. - This is prevented by checking the type of the node before attemping to set the defaults
1 parent 99a5389 commit 39cc79b

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/main/java/com/networknt/schema/PropertiesValidator.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
package com.networknt.schema;
1818

1919
import com.fasterxml.jackson.databind.JsonNode;
20+
import com.fasterxml.jackson.databind.node.JsonNodeType;
2021
import com.fasterxml.jackson.databind.node.ObjectNode;
2122
import com.networknt.schema.walk.DefaultPropertyWalkListenerRunner;
2223
import com.networknt.schema.walk.WalkListenerRunner;
@@ -114,7 +115,7 @@ private void addToEvaluatedProperties(String propertyPath) {
114115
@Override
115116
public Set<ValidationMessage> walk(JsonNode node, JsonNode rootNode, String at, boolean shouldValidateSchema) {
116117
HashSet<ValidationMessage> validationMessages = new LinkedHashSet<ValidationMessage>();
117-
if (applyDefaultsStrategy.shouldApplyPropertyDefaults()) {
118+
if (applyDefaultsStrategy.shouldApplyPropertyDefaults() && node.getNodeType() == JsonNodeType.OBJECT) {
118119
applyPropertyDefaults((ObjectNode) node);
119120
}
120121
if (shouldValidateSchema) {
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.networknt.schema;
2+
3+
import com.fasterxml.jackson.databind.JsonNode;
4+
import org.junit.jupiter.api.Assertions;
5+
import org.junit.jupiter.api.Test;
6+
7+
/**
8+
* Created by josejulio on 25/04/22.
9+
*/
10+
public class PropertiesValidatorTest extends BaseJsonSchemaValidatorTest {
11+
12+
@Test
13+
public void testDoesNotThrowWhenApplyingDefaultPropertiesToNonObjects() throws Exception {
14+
Assertions.assertDoesNotThrow(() -> {
15+
JsonSchemaFactory factory = JsonSchemaFactory.getInstance(SpecVersion.VersionFlag.V4);
16+
17+
SchemaValidatorsConfig schemaValidatorsConfig = new SchemaValidatorsConfig();
18+
schemaValidatorsConfig.setApplyDefaultsStrategy(new ApplyDefaultsStrategy(
19+
true,
20+
true,
21+
true
22+
));
23+
24+
JsonSchema schema = factory.getSchema("{\"type\":\"object\",\"properties\":{\"foo\":{\"type\":\"object\", \"properties\": {} },\"i-have-default\":{\"type\":\"string\",\"default\":\"foo\"}}}", schemaValidatorsConfig);
25+
JsonNode node = getJsonNodeFromStringContent("{\"foo\": \"bar\"}");
26+
ValidationResult result = schema.walk(node, true);
27+
Assertions.assertEquals(result.getValidationMessages().size(), 1);
28+
});
29+
}
30+
}

0 commit comments

Comments
 (0)