简体   繁体   中英

How to convert a string `to_json` and `to_xml` using Ruby on Rails?

I am using Ruby on Rails 3 and I would like, in some way, to convert a string to_json and to_xml .

Just to know, I need to return that string in a Rack method in this way:

[404, {"Content-type" => "application/json"}, ["Bad request"]]
# or
[404, {"Content-type" => "application/xml"}, ["Bad request"]]

However what I need is only to convert that string to_json and to_xml ? How is it possible do that?

Sometimes you must add a require 'json' in your file (after installing the gem, JSON implementation for Ruby ) and do:

JSON.parse("Bad request").to_json   

or you could try:

ActiveSupport::JSON.encode("Bad request").to_json

But in your case maybe the best approach is respond correctly:

respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @somearray }
  format.json  { render :json => @somearray }
end

Alternatively you could do:

  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

在您的控制器中,只需传入XML字符串:

render xml: "<myxml><cool>fff</cool></myxml>"

JSON follows JavaScript syntax, so a string in JSON is easy:

[404, {"Content-type" => "application/json"}, ["'Bad request'"]]

As for XML, the answer is not so simple. You'd have to decide what tag structure you want to use and go from there. Remember that an XML doc has, at a minimum, a root tag. So, you could return an XML doc like this:

<?xml version="1.0" encoding="utf-8"?>
<response>Bad request</response>

One way to do this would be to use the Builder gem:

http://builder.rubyforge.org/

However, I'm not entirely certain why you would need to return a string all by itself as JSON or XML. JSON and XML are typically used for transmitting structured data, eg arrays, nested data, key-value pairs, etc.. Whatever your client is, it could presumably just interpret the string as-is, without any JSON or XML ecoding, no?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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