Reputation: 2043
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+ " ]";
}
}
It is displying 95.9 but I wanted to display 95.90. Can someone please help?
Upvotes: 0
Views: 352
Reputation: 602
You can replace toString
body with following code snippet:
public String toString() {
return String.format("Student [ name: %s, age: %.02f]", name, percentage)
}
So you don't need to change double
to String
Upvotes: 3