I was hoping that by requiring json I’ll get a working “from_json” added to my struct, just as it happened to my NamedTuples, but this code does not work:
require "json"
struct Person
property name : String
property email : String
def initialize(@name, @email)
end
end
foo = Person.new("Foo", "me@foo.bar")
p! foo
json_str = %{{"name": "Bar", "email": "bar@foobar.com"}}
bar = Person.from_json(json_str)
p! bar
The output is
Showing last frame. Use --error-trace for full trace.
In /usr/share/crystal/src/json/from_json.cr:13:3
13 | new parser
^--
Error: wrong number of arguments for 'Person.new' (given 1, expected 2)
Overloads are:
- Person.new(name, email)
Apparently the from_json will call the initialize
method with a JSON::PullParser object.
I could use that to implement parsing of the JSON, but I wonder, is this the recommended way to do it?
require "json"
struct Person
property name : String
property email : String
def initialize(@name, @email)
end
def initialize(pull)
@name = ""
@email = ""
pull.read_object do |key|
case key
when "name"
@name = pull.read_string
when "email"
@email = pull.read_string
end
end
end
end
foo = Person.new("Foo", "me@foo.bar")
p! foo
json_str = %{{"name": "Bar", "email": "bar@foobar.com"}}
bar = Person.from_json(json_str)
p! bar