在此示例中,我们使用Google Gson将一个对象(Studentobject)转换为JSON表示法。实际上,我们可以使用该库来转换Java中的任何对象,这非常简单。您只需要创建一个Gson类的实例,然后调用该toJson()方法并将要转换的对象传递为JSON字符串。
package org.nhooo.example.google.gson; 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); } }
运行上面的示例时,您将获得类似以下的输出:
json = {"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}
下面是我们的Student课。
package org.nhooo.example.google.gson; import java.io.Serializable; import java.util.Date; public class Student implements Serializable { 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; } }
Maven依赖
<!-- http://repo1.maven.org/maven2/com/google/code/gson/gson/2.8.0/gson-2.8.0.jar --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency>