Take a look at this example: https://play.crystal-lang.org/#/r/4hqb
Here's the code (don't know how long that link is good for...)
require "json"
class House
JSON.mapping(address: String)
getter first_part
def initialize
@first_part = address.split(" ")[0]
end
end
house = House.from_json(%({"address": "Crystal Road 1234"))
puts house.first_part
It's the basics of the JSON.mapping example in the docs. Except I added an initialize
which does something with the JSON data (address).
The trouble is we get this error:
Error in line 8: this 'initialize' doesn't explicitly initialize instance variable '@address' of House, rendering it nilable
Questions:
- The default in mapping is 'nilable: false' and I don't want this to be nilable. Is there some way to expect this error to come from JSON which failed to specify address instead of making this a nilable field?
- It would seem that there is another initialize somewhere that I should override (and call super on) but so far I haven't been successful. If that's the right approach, how is it done?