-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!

0

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.