-1

I am trying to make an ruby object serialize to a json that gets digested by an API.

Thanks to this link I got to the point where I do not get an object in my Json but a string of values.{"@id":"32662787","@status":"Created","@dateTime":"2016-03-11T08:42:14.6033504"} But the problem is the leading @ in front of the names. Is there a way to get around that?

My object class I try to serialize:

   class Obj
  attr_accessor :id, :status, :dateTime
  def to_json
    hash = {}
    self.instance_variables.each do |var|
      hash[var] = self.instance_variable_get var
    end
    hash.to_json
  end
end

I do not want to use gems that are not included with ruby.

Thanks in advance!

Community
  • 1
  • 1
Faling Dutchman
  • 211
  • 1
  • 4
  • 17

1 Answers1

1

instance_variables returns variables with the @ (which is arguably a bit silly), which you can just strip it with string splicing:

hash[var[1..-1]] = ...

Full example:

require 'json'

class Obj
  attr_accessor :id, :status, :dateTime

  def to_json
    hash = {}
    self.instance_variables.each do |var|
      hash[var[1..-1]] = self.instance_variable_get var
    end
    hash.to_json
  end
end

a = Obj.new
a.id = 42
a.status = 'new'

puts a.to_json

Gives:

{"id":42,"status":"new"}

Note that we don't strip the @ for instance_variable_get, as it's required here (which is arguably also a bit silly, but at least it's consistent).

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146