The Gson tool class converts Java classes to JSON usage

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.