nikhil
nikhil

Reputation: 9415

Unable to parse json with ruby

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.

Upvotes: 3

Views: 439

Answers (2)

Abe Voelker
Abe Voelker

Reputation: 31622

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

Upvotes: 3

Jason Waldrip
Jason Waldrip

Reputation: 5148

Use as_json instead of to_json.

Upvotes: 0

Related Questions