1, XML to Hash
需要用到一个ruby gem: jnunemaker-crack,所以首先安装之:
gem install jnunemaker-crack -s http://gems.github.com
./script/console
>> xml = '<posts><post><title>Foobar</title></post><post><title>Another</title></post></posts>'
=> "<posts><post><title>Foobar</title></post><post><title>Another</title></post></posts>"
>> Crack::XML.parse(xml)
=> {"posts"=>{"post"=>[{"title"=>"Foobar"}, {"title"=>"Another"}]}}
2, JSON to Hash
同样需要用到ruby gem: jnunemaker-crack
./script/console
>> json = "{\"name\":\"张三\",\"gender\":\"boy\"}"
=> "{\"name\":\"张三\",\"gender\":\"boy\"}"
>> Crack::JSON.parse(json)
=> {"name"=>"张三", "gender"=>"boy"}
或者ActiveSupport::JSON.decode
>> json = "{\"name\":\"张三\",\"gender\":\"boy\"}"
=> "{\"name\":\"张三\",\"gender\":\"boy\"}"
>> ActiveSupport::JSON.decode json
=> {"name"=>"张\344\270\211", "gender"=>"boy"}
3, XML to JSON
require 'rubygems'
require 'activesupport'
xml = <<XML
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<imsRestResponse xmlns="com:ericsson:imsinnovation:rest:instantmsg"
xmlns:ns2="com:ericsson:imsinnovation:rest:users" xmlns:ns3="urn:ietf:params:xml:ns:pidf"
xmlns:ns4="urn:ietf:params:xml:ns:pidf:data-model" xmlns:ns5="com:ericsson:imsinnovation:rest:presence"
xmlns:ns6="urn:ietf:params:xml:ns:watcherinfo" xmlns:ns7="com:ericsson:imsinnovation:rest:userreq"
xmlns:ns8="com:ericsson:imsinnovation:rest">
<imMessages>
<imMessage>
<from>sip:bob@imsinnovation.com</from>
<content>
<Content-Type>text/plain</Content-Type>
<plainTxtContent>hello!</plainTxtContent>
</content>
</imMessage>
</imMessages>
</imsRestResponse>
XML
json = Hash.from_xml(xml).to_json
p json
输出:
"{'imsRestResponse':{'xmlns:ns7':'com:ericsson:imsinnovation:rest:userreq','xmlns:ns8':'com:ericsson:imsinnovation:rest','xmlns:ns2':'com:ericsson:imsinnovation:rest:users','imMessages':{'imMessage':{'from':'sip:bob@imsinnovation.com','content':{'plainTxtContent':'hello!','Content_Type':'text/plain'}}},'xmlns:ns3':'urn:ietf:params:xml:ns:pidf','xmlns:ns4':'urn:ietf:params:xml:ns:pidf:data-model','xmlns:ns5':'com:ericsson:imsinnovation:rest:presence','xmlns':'com:ericsson:imsinnovation:rest:instantmsg','xmlns:ns6':'urn:ietf:params:xml:ns:watcherinfo'}}"
4, Hash to XML and Hash to JSON
root@dev:/usr/local/system/work/dress# ./script/console
>> hash = { :one => 1, :two => 2}
=> {:one=>1, :two=>2}
>> hash.to_xml
=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<hash>\n <one type=\"integer\">1</one>\n <two type=\"integer\">2</two>\n</hash>\n"
>> hash.to_json
=> "{\"one\":1,\"two\":2}"
或者 ActiveSupport::JSON.encode
>> a = {"name"=>"张\344\270\211", "gender"=>"boy"}
=> {"name"=>"张\344\270\211", "gender"=>"boy"}
>> ActiveSupport::JSON.encode a
=> "{\"name\":\"\\u5f20\\u4e09\",\"gender\":\"boy\"}"
转载于:https://blog.51cto.com/writerok/710834