The example is how to convert a Student object to a JSON string, and in practice we can convert any Java class to a JSON string, and the implementation is very simple, you just need to create an Gson instance, then pass the object that will be converted to the JSON string, and invoke the instance's ToJ Son method. Import Com.google.gson.Gson;
Import Java.util.Calendar;
public class Studenttojson {
public static void Main (string[] args) {
Calendar dob = Calendar.getinstance ();
Dob.set (2000, 1, 1, 0, 0, 0);
Student Student = new Student ("Duke", "Menlo Park", Dob.gettime ());
Gson Gson = new Gson ();
String JSON = Gson.tojson (student);
SYSTEM.OUT.PRINTLN ("JSON =" + JSON);
}
}
Import Java.util.Date;
public class Student {
private String name;
Private String address;
Private Date dateOfBirth;
Public Student () {
}
Public Student (string name, string address, Date dateOfBirth) {
THIS.name = name;
this.address = address;
This.dateofbirth = dateOfBirth;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public String getaddress () {
return address;
}
public void setaddress (String address) {
this.address = address;
}
Public Date Getdateofbirth () {
return dateOfBirth;
}
public void Setdateofbirth (Date dateofbirth) {
This.dateofbirth = dateOfBirth;
}
}
The following are the output results:
JSON = {"name": "Duke", "Address": "Menlo Park", "dateOfBirth": "Feb 1, 12:00:00 AM"}
The Gson tool class converts Java classes to JSON usage