Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Struct from JSON - upper case

  • We cannot have attributes starting with upper case so we have to convert the field names to lowercase:
  • Using attribute annotation
require "json"

struct Person
  include JSON::Serializable

  getter name : String

  @[JSON::Field(key: "Email")]
  getter email : String
end

json_str = %{{"name": "Bar", "Email": "bar@foobar.com"}}
prs = Person.from_json(json_str)
p! prs
p! prs.name
p! prs.email
prs # => Person(@name="Bar", @email="bar@foobar.com")
prs.name # => "Bar"
prs.email # => "bar@foobar.com"