在这里开始 Rails 程序员。我正在尝试将哈希转换为 xml 和 json,但输出不同。
这是哈希:
{:exchangeRates=>[{:baseCurrency=>"USD", :quoteCurrency=>"EUR", :amount=>1, :nprices=>1, :conversions=>[{:date=>Tue, 20 Nov 2012 21:00:00 +0000, :ask=>"0.7813", :bid=>"0.7813"}]}, {:baseCurrency=>"CAD", :quoteCurrency=>"EUR", :amount=>1, :nprices=>1, :conversions=>[{:date=>Tue, 20 Nov 2012 21:00:00 +0000, :ask=>"0.7839", :bid=>"0.7837"}]}]}
这是相应的渲染代码
format.json { render :json => { :response => rates.to_hash() } }
这是JSON(这就是我想要的)
{"response": {"exchangeRates": [
{
"baseCurrency": "USD",
"quoteCurrency": "EUR",
"amount": 1,
"nprices": 1,
"conversions": [{
"date": "2012-11-20T21:00:00+00:00",
"ask": "0.7813",
"bid": "0.7813"
}]
},
{
"baseCurrency": "CAD",
"quoteCurrency": "EUR",
"amount": 1,
"nprices": 1,
"conversions": [{
"date": "2012-11-20T21:00:00+00:00",
"ask": "0.7839",
"bid": "0.7837"
}]
}
]}}
这是我的 xml 渲染代码:
format.xml { render :xml => rates.to_hash(), :root => 'response' }
这是 xml 输出(我在数组中放置了额外的标签):
<response>
<exchangeRates type="array">
<exchangeRate>
<baseCurrency>USD</baseCurrency>
<quoteCurrency>EUR</quoteCurrency>
<amount type="integer">1</amount>
<nprices type="integer">1</nprices>
<conversions type="array">
<conversion>
<date type="datetime">2012-11-20T21:00:00+00:00</date>
<ask>0.7813</ask>
<bid>0.7813</bid>
</conversion>
</conversions>
</exchangeRate>
<exchangeRate>
<baseCurrency>CAD</baseCurrency>
<quoteCurrency>EUR</quoteCurrency>
<amount type="integer">1</amount>
<nprices type="integer">1</nprices>
<conversions type="array">
<conversion>
<date type="datetime">2012-11-20T21:00:00+00:00</date>
<ask>0.7839</ask>
<bid>0.7837</bid>
</conversion>
</conversions>
</exchangeRate>
</exchangeRates>
</response>
如您所见,它添加了额外的“数组”属性标签,即exchangeRates 和conversions。我如何让它的格式与 json 相同?我也不想要任何标签上的属性。我知道你可以传入属性,例如 :root => 'response',但是在寻找了相当长的一段时间后,我似乎无法在网上找到这些属性的列表。
任何帮助将不胜感激,谢谢!