Search code examples
crystal-lang

Force empty strings to raise exception when using Crystal's JSON.mapping macro


Is it possible to force JSON.mapping to raise a parse exception if/when a string member is present, but its value is the empty string?

I've tried using the available options (presence, nilable, etc.) to no avail. I've also experimented with writing a custom converter -- it looks like this will probably work -- but I want to make sure I'm not missing a simple solution to what seems like it should be a pretty common use case.


Solution

  • Here's a way to tack custom validation code onto the method produced by JSON.mapping

    require "json"
    
    struct Foo
      JSON.mapping(field: String)
    
      def initialize(pull : JSON::PullParser)
        previous_def
        raise JSON::Error.new("empty field") if field.empty?
      end
    end
    
    Foo.from_json(%({"field": ""}))