对象序列化和反序列化在红宝石(库),XML和JSON?

问题描述 投票:4回答:2

我在寻找一种方式来序列化/从XML / JSON表示deseialize的对象。

我不担心XML命名空间。

是否有任何的Ruby允许我这样做:

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

从.NET背景的,我找的一些东西,让我消耗从RESTful Web服务/分派对象。

你如何消耗轨web服务? (XML和JSON)。使用XPath /活动资源似乎有点太冗长(即使是净人)

使用Ruby 1.9.x的,Rails的3.X

谢谢

ruby-on-rails ruby serialization
2个回答
1
投票

由于您使用Rails,Rails的(通过的ActiveSupport)已经提供了一种序列化/在YAML,XML和JSON反序列化对象。

例如

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的的已知,如何序列化/反序列化它们。

我写了一篇关于serializing and deserializing objects in Ruby using JSON的文章。以下是关于serialization features of ActiveModel的文档。


0
投票

你应该考虑roar gem

渲染

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
© www.soinside.com 2019 - 2024. All rights reserved.