【发布时间】:2020-06-22 17:47:37
【问题描述】:
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class StudentMain {
public static void main(String[] args) {
String jsonString = "{\"name\":\"XYZ\", \"percentage\":95.90}";
GsonBuilder builder = new GsonBuilder();
builder.setPrettyPrinting();
Gson gson = builder.create();
Student student = gson.fromJson(jsonString, Student.class);
System.out.println(student.getPercentage());
}
}
package com.json;
class Student {
private String name;
private double percentage;
public Student(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public String toString() {
return "Student [ name: "+name+", age: "+ percentage+ " ]";
}
}
显示 95.9 但我想显示 95.90。 有人可以帮忙吗?
【问题讨论】:
-
将其更改为您希望在 toString 方法中看到的格式。
-
将百分比存储为字符串而不是双精度
-
谢谢@Jens。我现在很好。
-
@MT756 为什么打印输出只需要 thenformat 时要存储为字符串?
-
@Jens 我没有看到打印字符串的问题。只要您不对百分比进行任何数学运算,字符串就足够了。
标签: java json web-services web gson