Struct from JSON missing data (optional fields)
examples/struct/struct_from_json_missing_data.cr
require "json" struct Person include JSON::Serializable getter name : String getter email : String getter address : String? end json_str = %[{ "name": "Bar", "email": "bar@foobar.com", "address" : "my address" }] prs = Person.from_json(json_str) pp! prs p! prs.name p! prs.address puts "" json_str = %[{ "name": "Bar", "email": "bar@foobar.com" }] prs = Person.from_json(json_str) pp! prs p! prs.name p! prs.address
prs # => Person(@address="my address", @email="bar@foobar.com", @name="Bar") prs.name # => "Bar" prs.address # => "my address" prs # => Person(@address=nil, @email="bar@foobar.com", @name="Bar") prs.name # => "Bar" prs.address # => nil