SharePoint Newbie
SharePoint Newbie

Reputation: 6082

Object Serialization and Deserialization for XML and JSON in Ruby (library)?

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

Upvotes: 4

Views: 3522

Answers (2)

Oshan Wisumperuma
Oshan Wisumperuma

Reputation: 1958

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

Upvotes: 0

Simone Carletti
Simone Carletti

Reputation: 176562

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.

Upvotes: 1

Related Questions