简体   繁体   English

Ruby on Rails JSON序列化

[英]Ruby on Rails JSON serialization

I'm a complete newcomer to Ruby on Rails so please forgive me if this is an obvious question. 我是Ruby on Rails的新手,所以如果这是一个明显的问题,请原谅我。

I'm returning a JSON object from a controller method (let's say the class name is "foo" and it has a property "bar"). 我从控制器方法返回一个JSON对象(假设类名是“foo”,它有一个属性“bar”)。

I'd expected this to serialize as: 我希望这可以序列化为:

{"bar" : "barValue" }

However, it seems to serialize as 但是,它似乎序列化为

{"foo" : {"bar" : "barValue"}}

This seems out of joint with a.) what other languages do , b.) (More importantly) what javascript does. 这似乎与a。)其他语言的关联,b。)(更重要的是)javascript的作用。

Say I've defined the same class foo in Javascript: 假设我在Javascript中定义了相同的类foo:

var fooInstance = new Foo();
fooInstance.bar = "barValue";

And I then stringify that using one of a Javascript JSON library (eg https://github.com/douglascrockford/JSON-js ). 然后我使用一个Javascript JSON库(例如https://github.com/douglascrockford/JSON-js )对其进行字符串化。 Then the output is something along the lines of: 然后输出是这样的:

{"bar" : "barValue" }

But inputs (as well as outputs) to my controller methods expect: 但是我的控制器方法的输入(以及输出)期望:

{"foo" : {"bar" : "barValue"}

So I have to write code along these lines to make it work: 所以我必须沿着这些行编写代码才能使它工作:

var fooInstance = new Foo();
fooInstance.bar = "barValue";
var dummyObjectToKeepRailsHappy = { foo : fooInstance};

So- am I doing Rails serialization incorrectly? 所以我做Rails序列化不正确吗? Or is there a reason it works this way? 或者它有这样的原因吗?

Read up the documentation on Rails to_json here . 这里阅读有关Rails to_json的文档。

The option ActiveRecord::Base.include_root_in_json controls the top-level behavior of to_json. ActiveRecord :: Base.include_root_in_json选项控制to_json的顶级行为。 In a new Rails application, it is set to true in initializers/new_rails_defaults.rb. 在新的Rails应用程序中,它在initializers / new_rails_defaults.rb中设置为true。 When it is true, to_json will emit a single root node named after the object's type. 如果为true,to_json将发出以对象类型命名的单个根节点。

So adding to your environment/application.rb 所以添加到您的环境/ application.rb

config.active_record.include_root_in_json = true

should solve your issues. 应该解决你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM