use*_*052 2 ruby xml json ruby-on-rails ruby-on-rails-3
我正在使用Ruby on Rails 3,我想以某种方式转换字符串to_json和to_xml.
要知道,我需要以这种方式在Rack方法中返回该字符串:
[404, {"Content-type" => "application/json"}, ["Bad request"]]
# or
[404, {"Content-type" => "application/xml"}, ["Bad request"]]
Run Code Online (Sandbox Code Playgroud)
但是我需要的只是转换那个字符串to_json和to_xml?怎么可能那样做?
有时您必须require 'json'在文件中添加一个(在安装gem之后,为Ruby的JSON实现)并执行:
JSON.parse("Bad request").to_json
Run Code Online (Sandbox Code Playgroud)
或者你可以尝试:
ActiveSupport::JSON.encode("Bad request").to_json
Run Code Online (Sandbox Code Playgroud)
但在您的情况下,最好的方法可能是正确响应:
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @somearray }
format.json { render :json => @somearray }
end
Run Code Online (Sandbox Code Playgroud)
或者你可以这样做:
mystring_json = '{"bar":"foo"}'
[404, {'Content-Type' => 'application/json'}, [mysrting_json]] #json stuff
mystring_xml = '<?xml><bar>foo</bar>'
[404, {'Content-Type' => 'application/xml'}, [mysrting_xml]] #xml stuff
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17008 次 |
| 最近记录: |