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

I'm not interested in xml namespaces.

Is there anything in Ruby that 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

Based on the .Net background, I am looking for something that allows me to consume / send objects from quiet web services.

How do you use web services on rails? (xml and json). Using xpath / active resource seems too verbose (even for .Net person)

Using ruby ​​1.9.x, Rails 3.x

thank

+4
source share
2 answers

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

for instance

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\"}"

ActiveRecord, Rails , / .

Ruby JSON. ​​ ActiveModel.

+1

Rendering

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

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

Source: https://habr.com/ru/post/1789177/


All Articles