gson에서 json으로 serialize/deserialize 할 때 float 값을 표시하는 데 문제가 있습니다. 대신 fx를 표시하는 대신 부동 소수점을 제거합니다. 745.0은 디스플레이 745입니다. 어떤 아이디어일까요?parseFloat gson json string
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"));
});
}
});
});
그냥 v.rate.toFixed (2)를 사용할 수 있습니다. –