4

I am looking for a way to serialize/deseialize an object from its xml/json representation.

I am not concerned about xml namespaces.

Is there anything in Ruby which allows me to do:

class Person
   attr :name, true
   attr :age, true
   attr :sex, true
end

person_xml =
"<Person>
  <name>Some Name</name>
  <age>15</age>
  <sex>Male</male>
</Person>"

// and then do
p = person_xml.deserialize(Person.class)
// or something of that sort

Coming from a .Net background, I am looking for something which lets me consume/dispatch objects from restful web services.

How do you consume webservices in rails? (xml and json). Using xpath/active resource seems a bit too verbose (even for a .Net person)

Using ruby 1.9.x, Rails 3.x

Thanks

2 Answers 2

1

Because you are using Rails, Rails (via ActiveSupport) already provides a way to serialize/deserialize objects in YAML, XML and JSON.

For example

class Post
  attr_accessor :title
  attr_accessor :body
end

post = Post.new.tap do |p|
  p.title = "A title"
  p.body = "A body"
end

post.to_yaml
# => "--- !ruby/object:Post \nbody: A body\ntitle: A title\n"

post.to_json
# => => "{\"body\":\"A body\",\"title\":\"A title\"}"

If you are using ActiveRecord models, then Rails knowns how to serialize/deserialize them.

I wrote an article about serializing and deserializing objects in Ruby using JSON. Here's the documentation about the serialization features of ActiveModel.

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

5 Comments

What about using it outside of rails? We need to consume a couple of different webservices and wanted to deserialize the resonses to objects so that we could easily manipulate them.
You don't need Rails. If you include ActiveSupport as requirement, you can take advantage of almost the same features. Otherwise, simply use the JSON library alone.
I am specifically looking for a way to deserialize to an object.
Hi, Thanks for the help. The decode method returns a hash. I am looking for something to which gives me an object of a given class.
You should implement that feature. Otherwise use YAML. YAML.dump && YAML.load.
0

you should consider roar gem

Rendering

song = Song.new(title: "Medicine Balls")
SongRepresenter.new(song).to_json #=> {"title":"Medicine Balls"}

Parsing

song = Song.new(title: "Medicine Balls")
SongRepresenter.new(song).from_json('{"title":"Linoleum"}')
song.title #=> Linoleum

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.