gpt4 book ai didi

java - GSON - Json 到 Java 解析 - 如何保留尾随零

转载 作者:行者123 更新时间:2023-12-01 19:28:29 25 4
gpt4 key购买 nike

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 正文替换为以下代码片段:

public String toString() { 
return String.format("Student [ name: %s, age: %.02f]", name, percentage)
}

所以你不需要将double更改为String

关于java - GSON - Json 到 Java 解析 - 如何保留尾随零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60624245/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com