【问题标题】:Render simple JSON array with RABL in Rails在 Rails 中使用 RABL 渲染简单的 JSON 数组
【发布时间】:2014-02-14 12:41:09
【问题描述】:

我一直在想办法让 RABL 渲染一个非常简单的 JSON 字符串数组,例如:["my,"array","of","strings"]

控制器是

class StringsController < ApplicationController
    responds_to :json

    def index
        @string = ['my','array','of','strings']
        respond_with @strings
    end

end

RABL 视图必须从以下内容开始:

collection @strings, root_object: false

但我不知道如何只输出没有节点名称或对象内的字符串...

显然有一个更直接的解决方案来实际提供 JSON 数组,就像我在下面所说的那样,但我特别感兴趣的是为什么这在 RABL 中看起来如此复杂!

class StringsController < ApplicationController

    def index
        render json: ['my','array','of','strings']
    end

end

【问题讨论】:

  • 在 rabl 中,集合将采用 json 对象而不是数组。

标签: ruby-on-rails json rabl


【解决方案1】:

尼尔,

这应该适用于任何数组,但对于您的特定数组,确切答案是......

在 index.json.rabl 中使用下面的代码

collection @string, object_root: false

node do |s|
  s 
en

在您的控制器中使用...

def index 
    @string = ["my","array","of","strings"]
end

【讨论】:

  • 恐怕这对我不起作用。您提供的 RABL 模板生成 JSON [{},{},{}],而不是 ['my','array','of','strings'](我使用的是 RABL 版本 0.9.3,如果这有什么不同的话)
  • 我看到你的数组在@string中,现在试试,但不要respond_with,只需使用render并在index.json.rabl中使用我的响应
  • 我尝试将其设置为 RABL 模板上的视图规范,因此它与控制器分离,它仍然只呈现空对象而不是字符串。
  • 我注意到的一件事是您的数组被称为 [at]string 并且集合是 [at]strings。尝试更改集合名称以匹配您正在使用的变量。你不应该只需要一个 render 调用。
  • 哎呀..!不幸的是,这只是我在开篇文章中的一个错字:) 仍然没有运气,我是否使用#respond_to 都没有关系,。我得到空对象数组。我决定改用 jbuilder,这让我可以轻松地做到这一点。似乎放弃了,但我花了很多时间试图找出如何让这个简单的表示工作......
【解决方案2】:

为了建立在马克的回答之上,我认为它适用于:

collection @string, object_root: false

node :value do |s|
  s 
end

注意,我添加了:value,这是 JSON 记录的标签。

【讨论】:

  • 有没有办法让动态键而不是静态键作为值??
【解决方案3】:

您可以这样做,并且不需要 rabl 视图来显示响应。

def index
    @string = ['my','array','of','strings']
    respond_to do |format|
      format.json  { render :json => {:message => "Success", :my_string => @string } }
      format.xml
    end
  end

【讨论】:

  • 该解决方案不会呈现简单的字符串数组,也没有回答我关于使用 RABL 呈现数组的问题。我希望 JSON 输出简单地为 ["my,"array","of","strings"],虽然还有其他方法,但我想具体了解如何在 RABL 中实现这一点。
猜你喜欢
  • 2012-02-14
  • 1970-01-01
  • 2011-12-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-11
相关资源
最近更新 更多