gpt4 book ai didi

ruby-on-rails - Ruby(库)中 XML 和 JSON 的对象序列化和反序列化?

转载 作者:数据小太阳 更新时间:2023-10-29 07:38:36 28 4
gpt4 key购买 nike

我正在寻找一种从对象的 xml/json 表示中序列化/反序列化对象的方法。

我不关心 xml namespace 。

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 网络服务中消费/调度对象的东西。

如何在 Rails 中使用 Web 服务? (xml 和 json)。使用 xpath/active 资源似乎有点过于冗长(即使对于 .Net 用户也是如此)

使用 ruby​​ 1.9.x、Rails 3.x

谢谢

最佳答案

因为您使用的是 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 的文档.

关于ruby-on-rails - Ruby(库)中 XML 和 JSON 的对象序列化和反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4860101/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com