【问题标题】:GSON - Json to Java parsing - How to keep the trailing zeroGSON - Json 到 Java 解析 - 如何保持尾随零
【发布时间】: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


【解决方案1】:

您可以将toString body 替换为以下代码 sn-p:

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

因此您无需将double 更改为String

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 2018-02-03
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多