【发布时间】:2013-12-15 17:54:55
【问题描述】:
在使用 gson 对 json 进行序列化/反序列化时,将值显示为浮点数时出现问题。相反,它会删除浮点数,而不是显示 fx。 745.0 是显示 745。知道为什么吗? 下面是通过命令模式生成的后端代码:
public String execute(HttpServletRequest request, HttpServletResponse response, CurrencyClient client) {
String currency = client.findAll_JSON(String.class);
Gson gson = new Gson();
Currency[] currencies = gson.fromJson(currency, Currency[].class);
System.out.println("currencies " + currencies[0].getRate());
response.setContentType("application/json;charset=UTF-8");
try (PrintWriter pw = response.getWriter()) {
//System.out.println("JSON " + currencies);
MyObject myObject = new MyObject();
for (Object c : currencies) {
myObject.add((gson.toJson(c)));
}
System.out.println("value of rate: " + gson.toJson(myObject.getCurrencies()));
pw.println(gson.toJson(myObject));
pw.close();
} catch (IOException e) {
e.printStackTrace();
}
return super.execute(request);
}
}
类 MyObject {
ArrayList<Object> currencies = new ArrayList<Object>();
public MyObject() {
}
public void add(Object e){
this.currencies.add(e);
}
public Object getCurrencies() {
return currencies;
}
public void setCurrencies(ArrayList<Object> currencies) {
this.currencies = currencies;
}
以及客户端代码:
$(document).ready(function() {
$.ajax({
url: "Controller",
cache: false,
dataType: "json",
data: {command: 'getCurrencyRates'},
success: function(data) {
$.each(data.currencies, function(index, value) {
var v = JSON.parse(value);
console.log(rate);
$("<tr><td>" + v.code + "</td><td>" + v.description + "</td><td>" + v.rate + "</td></tr>")
.appendTo($("table"));
});
}
});
});
【问题讨论】:
标签: json jsp servlets command gson