Gson 是一个由 Google 创建的用于 Java 的 json 库,它可以用来生成 JSON。通过使用 Gson,我们可以生成 JSON 并将一个 bean/ java 对象转换为 JSON 对象。我们可以调用 Gson 类的 toJson() 方法将 Java 对象转换为 JSON 对象。
语法
public java.lang.String toJson(java.lang.Object src)
登录后复制
示例
import com.google.gson.Gson;
public class ConvertJavaObjectToJSONTest {
public static void main(String[] args) {
Gson gson = new Gson();
Student student = new Student("Raja", "Ramesh", 30, "Hyderabad");
System.out.println(gson.toJson(student)); // converts java object to json object.
}
}
// student class
class Student {
private String firstName;
private String lastName;
private int age;
private String address;
public Student(String firstName, String lastName, int age, String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString() {
return "Student[ " +
" firstName = " + firstName +
", lastName = " + lastName +
", age = " + age +
", address = " + address +
" ]";
}
}
登录后复制
输出
{"firstName":"Raja","lastName":"Ramesh","age":30,"address":"Hyderabad"}
登录后复制
以上就是在Java中使用Gson库将Java对象转换为JSON?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!