如何在 Ruby 属性方法(ActiveModel::Serialization)中包含对象?

How to include object in Ruby attributes method (ActiveModel::Serialization)?

我有一个对象要序列化为 JSON,我正在尝试使用 ActiveModel::Serialization::JSON 模块来实现此目的。我的属性方法看起来像这样:

class MyClass
include ActiveModel::Serializers::JSON

def attributes
{
  'attr1' => nil,
  'attr2' => nil,
  'object1' => nil,
  'object2' => nil
}
end

在我尝试 运行 JSON.parse(myclass_instance.as_json.to_s) 之前这一切正常;我收到与 MyClass 中的内部对象相关的错误:

JSON::ParserError: 757: unexpected token at '{"object1"=>#<MyClass::object1_field1>...}'

如何在属性方法中指定我的内部对象,以免发生这种情况?

as_json函数比较特殊,return是JSON结构中的,但实际上并不是return JSON.

你要的是这个:

JSON.parse(instance.to_json)

看看 as_json 发出了什么。