3

I have created the following class

  class Contact
    def initialize(id, name, phone)
      @id = id
      @name = name
      @phone = phone
    end

    def to_json(*a)
      {
        json_class: self.class.name,
        data: { id: @id, name: @name, phone: @phone }
      }.to_json(*a)
    end

    def self.json_create(o)
      new( o[:data][:id], o[:data][:name], o[:data][:phone] )
    end
  end

I can now convert it to json using this

Contact.new(1,'nik',10).to_json
 => "{\"json_class\":\"Contact\",\"data\":{\"id\":1,\"name\":\"nik\",\"phone\":10}}" 

But it explodes with an error when I call JSON.parse on the it.

JSON.parse(Contact.new(1,'nik',10).to_json)
NoMethodError: undefined method `[]' for nil:NilClass
    from (irb):44:in `json_create'

I picked up the syntax from this tutorial.

2 Answers 2

3

Get rid of the symbols in your json_create method.

def self.json_create(o)
  new( o['data']['id'], o['data']['name'], o['data']['phone'] )
end
Sign up to request clarification or add additional context in comments.

3 Comments

That did the trick, could you tell me why what i did is wrong, I was under the impression that symbols and strings could be used interchangeably and symbols had better performance.
Symbols and strings are different objects. Symbols are always a reference to the same object, whereas strings are new objects each time referenced (unless stored in a variable).
What @AndréSantosdeMedeiros said is correct. The behavior you are thinking of is something that comes with Rails, which provides a HashWithIndifferentAccess that lets you use either the symbol or string form of the key to access the value.
0

Use as_json instead of to_json.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.