将对象序列化为JSON,XML,YAML? [英] Serializing an object to JSON, XML, YAML?

查看:164
本文介绍了将对象序列化为JSON,XML,YAML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我问了一个有关序列化和验证的先前问题.有人提到使用JSON gem,这使我可以告诉我的对象如何使用to_json方法进行序列化,但是Ruby似乎很容易完成很多复杂的事情,但是从另一方面来说,一些非常简单的事情似乎非常复杂,序列化就是其中之一.

I asked a previous question about serialization and validation. Someone mentioned using the JSON gem which allows me to tell my object how to serialize with the to_json method, however Ruby seems to do LOTS of complicated things really easily, however on the flip side some really simple things seem to be quite complicated, Serialization being one of those things.

我想找出是否有一种方法可以清除对象:

I want to find out if there is a way to have a clean object:

class CleanClass
    attr_accessor :variable1
    attr_accessor :variable2
    attr_accessor :variable3
end

cleanObject = CleanClass.new

理想情况下,我不想弄脏模型,我只想将其传递给 something 并告诉它输出类型应该是什么,并使其发挥作用.

Ideally, I don't want to dirty the model, I just want to pass it to something and tell it what the output type should be and let it work its magic.

例如:

jsonOutput = MagicSerializer::Json.Serialize(cleanObject)
xmlOutput = MagicSerializer::Xml.Serialize(cleanObject)
yamlOutput = MagicSerializer::Yaml.Serialize(cleanObject)

revertedJsonObject = MagicSerializer::Json.Unserialize(jsonOutput)
revertedXmlObject = MagicSerializer::Xml.Unserialize(xmlOutput)
revertedYamlObject = MagicSerializer::Yaml.Unserialize(yamlOutput)

我想传递一个对象,并输出字符串,然后将其转换回去.

I want to pass something an object, and get the strings outputted, then be able to convert it back.

我知道ActiveModel具有序列化功能,但是我需要弄脏我的类才能做到这一点,并且如果可能的话,我不想更改模型. ActiveSupport似乎满足JSON标准,因为我可以调用它,它将带一个对象并吐出JSON,但我想支持其他类型.

I know ActiveModel has serialization functionality but I need to dirty my class to do this, and I don't want to change the model if possible. ActiveSupport seems to satisfy the JSON criteria as I can just call that and it will take an object and spit out the JSON, but I would like to support other types.

任何进一步的信息都将很棒!

Any further information would be great!

推荐答案

Ruby内置了对二进制和yaml的自动幻化序列化/反序列化功能.

Ruby has built-in automagical serialization/deserialization to binary and yaml.

Yaml:

require 'yaml'
serialized = CleanClass.new.to_yaml
object = YAML.load(serialized)

元帅:

serialized = Marshal.dump(CleanClass.new)
object = Marshal.load(serialized)

这篇关于将对象序列化为JSON,XML,YAML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆