8

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?

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
user686249
  • 669
  • 6
  • 17
  • If an empty yaml file is valid, you could report it as a bug, though I guess this could be a design decision. Anyway, I would just catch the exception and move on. – kapex Feb 20 '15 at 13:08
  • 2
    @kapep: Yes, that's what I'm doing for now. ATM I'm falling back to the default configuration also in case of actual errors in the file, so it doesn't matter much. But should I decide to treat errors differently (e.g. terminate noisily), I'd end up comparing the exception message to distinguish errors from the empty file case, which I'd find very ugly. – user686249 Feb 20 '15 at 20:42

1 Answers1

2

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.

Anthon
  • 69,918
  • 32
  • 186
  • 246
  • 1
    As stated in my question the parser throws an exception, so that's the only thing I could check. – user686249 Jun 07 '15 at 10:33
  • @user686249 I don't know the parsernames used by your parser, but "com.fasterxml.jackson.databind.JsonMappingException" looks more like a application than a YAML parser to me. Not that that helps you solve the issue, but it will be for where to report the bug. – Anthon Jun 07 '15 at 10:58