For a config file format I'd like to use YAML and Jackson to read it. So I have a POJO class Configuration
with a few properties and simply read a respective object directly from the file via ObjectMapper.readValue()
.
In principle that works fine, unless the configuration file is -- except for comments -- empty. Then the exception
com.fasterxml.jackson.databind.JsonMappingException: No content to map due to end-of-input
is thrown. Since there are defaults for all configuration values, not specifying a value for any of them should be just fine, so I'd like to allow that. Is there any way to convince Jackson to accept an empty file?
An empty YAML file is a valid YAML file with a scalar that is NULL by absence of any specific value.
In YAML a blank value is interpreted as null, so whats the differance? Just use None . It will get interpreted the same way. Unless, of course, there is some very specific reason you need it to be blank regardless of how it is interpreted.
We can read the YAML file using the PyYAML module's yaml. load() function. This function parse and converts a YAML object to a Python dictionary ( dict object). This process is known as Deserializing YAML into a Python.
go mod init example.com/whatever go get gopkg.in/yaml.v3 cat go. sum go run . The tags (like yaml:"field" ) are optional for all-lowercase yaml key identifiers. For shows I've included a random camelCase identifier which does require such a tag.
If the top level of your YAML file is not a sequence or a mapping, it is a scalar. That way you can have a YAML file consisting of only a string (or a number). If a scalar value is empty, in a list, as value in a mapping it is equivalent to the NULL scalar value represented as (nil
for Ruby, None
for Python).
An empty YAML file is a valid YAML file with a scalar that is NULL by absence of any specific value.
Now single scalar only files are seldom useful, normally the toplevel is a mapping or a sequence or some derived complex type. It seems your applications assume that the toplevel is of the appropriate complex type and doesn't check for the parser to return NULL, and it should check.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With