简体   繁体   中英

How to add default values from JSON schema to JSON document in Java

I need to validate a JSON document AND add default values defined in the schema if the values are missing in the given document. I'm using networknt/json-schema-validator for validation, but I'm not sure how to go about adding default values. Is there a way to do that using the library above, or some other tool that would let me do that?

There's not a well defined way to do this in JSON Schema.


While there is a "default" keyword in JSON Schema, it's primarily for user interface usage, to provide a default initial value. Consider the schema:

{ "type":"string", "minLength":1, "default":"" }

In this case, the meaning is "when I create an instance of this schema, give it an initial value of an empty string."

First, note how this default document will still be invalid—it must be changed by the user before it will become valid. The "default" merely needs to be well-formed JSON. It's provided because, in this case, a blank string is a better default than an empty document (which would be invalid JSON).

Second, JSON Schema doesn't assume that that an undefined value is the same as the provided default value. Filling in undefined properties with default values is allowed to change the meaning of the instance. For example, given this schema:

{ "properties":
    "port": { "type":"number", "default": 80 }
}

It might be the case that an undefined property means one thing, but once I create that property, it should default to 80.

Third, the "default" keyword doesn't even apply unless the instance exists so that the keyword may be considered. If you're trying to fill in properties in an object, in order for the JSON Schema validator to "see" the "default" keyword, it has to first apply the instance against a schema with such a keyword.

Using the schema above, if you have an instance like {} , the validator will never even encounter the "default" keyword because the instance has no "port" property that would load the sub-schema containing it.


I'm not aware of a library that can do anything like what you're describing.

However if you want to write one, I would suggest writing a schema like this instead:

{
  "default": {
    "port": 80
  },
  "properties": {
    "port": { "type":"integer" }
  }
}

This would make the value of the "default" keyword accessible to the validator, even when the "port" property is missing. Your could then program a short script that merges in any missing properties.

See https://github.com/json-schema-org/json-schema-spec/issues/858 for a similar in the JSON Schema issue tracker.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM