使用GSON将Java对象转换为JSON

x33g5p2x  于2022-10-07 转载在 Java  
字(6.1k)|赞(0)|评价(0)|浏览(636)

在本文中,我们将创建一个使用GSON library将Java对象转换或序列化为JSON表示的示例。

Gson是一个Java库,可用于将Java对象转换为其JSON表示形式。它还可以用于将JSON字符串转换为等效的Java对象。Gson可以处理任意Java对象,包括您没有源代码的预先存在的对象。在这个例子中,我们将向您展示如何使用GSON将Java对象序列化为JSON。

GSON Maven依赖项

要在Maven2/3中使用Gson,可以通过添加以下依赖项来使用Maven Central中的Gson版本:

<dependencies>
    <!--  Gson: Java to Json conversion -->
    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.5</version>
      <scope>compile</scope>
    </dependency>
</dependencies>

学生POJO类-要序列化的对象

让我们创建一个Student类,它与e1d1e1类有一对多关系。让我们创建StudentPhone类,并使用GSON将其序列化为JSON表示。

class Student {

    private long studentId;
    private String studentName;
    private Set < Phone > studentPhoneNumbers = new HashSet < Phone > (0);

    public long getStudentId() {
        return studentId;
    }

    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Set < Phone > getStudentPhoneNumbers() {
        return studentPhoneNumbers;
    }

    public void setStudentPhoneNumbers(Set < Phone > studentPhoneNumbers) {
        this.studentPhoneNumbers = studentPhoneNumbers;
    }

    @Override
    public String toString() {
        return "Student [studentId=" + studentId + ", studentName=" + studentName + ", studentPhoneNumbers=" +
            studentPhoneNumbers + "]";
    }

}

class Phone {

    private long phoneId;
    private String phoneType;
    private String phoneNumber;

    public Phone() {}

    public Phone(String phoneType, String phoneNumber) {
        this.phoneType = phoneType;
        this.phoneNumber = phoneNumber;
    }

    public long getPhoneId() {
        return phoneId;
    }

    public void setPhoneId(long phoneId) {
        this.phoneId = phoneId;
    }

    public String getPhoneType() {
        return phoneType;
    }

    public void setPhoneType(String phoneType) {
        this.phoneType = phoneType;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
}

使用GSON将Java对象序列化或转换为JSON

在使用GSON将Java Object转换为JSON时,很高兴了解以下几点:

*不能用循环引用序列化对象,因为这将导致无限递归。
*Google GSON支持预先存在的对象。这意味着我们不需要用任何特殊的标记注释来注释类。
*序列化或反序列化时,默认情况下忽略瞬态字段。
*序列化时,将从输出中跳过空字段。
*反序列化时,JSON中缺少条目会导致将对象中的相应字段设置为null。
*与内部类、匿名类和本地类中的外部类对应的字段将被忽略,并且不会包含在序列化或反序列化中。

package net.javaguides.gson;

import java.util.HashSet;
import java.util.Set;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
* 
* @author Ramesh Fadatare
*
*/
public class GSONComplexObjectExample {
    public static void main(String[] args) {
        serializeStudentObject();
    }

    private static void serializeStudentObject() {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Student student = createStudent();
        String jsonStr = gson.toJson(student);
        System.out.println(jsonStr);
    }

    private static Student createStudent() {
        Student student = new Student();
        student.setStudentId(1000);
        student.setStudentName("Ramesh");
        Set < Phone > phones = new HashSet < Phone > ();
        Phone phone = new Phone();
        phone.setPhoneId(100);
        phone.setPhoneNumber("1234567890");
        phone.setPhoneType("Mobile Phone");
        phones.add(phone);

        Phone phone1 = new Phone();
        phone1.setPhoneId(101);
        phone1.setPhoneNumber("2222 3333 44");
        phone1.setPhoneType("Landline Phone");
        phones.add(phone1);

        student.setStudentPhoneNumbers(phones);
        return student;
    }
}

输出:

{
  "studentId": 1000,
  "studentName": "Ramesh",
  "studentPhoneNumbers": [
    {
      "phoneId": 100,
      "phoneType": "Mobile Phone",
      "phoneNumber": "1234567890"
    },
    {
      "phoneId": 101,
      "phoneType": "Landline Phone",
      "phoneNumber": "2222 3333 44"
    }
  ]
}

完整示例供参考

package net.javaguides.gson;

import java.util.HashSet;
import java.util.Set;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
* 
* @author Ramesh Fadatare
*
*/
public class GSONComplexObjectExample {
    public static void main(String[] args) {
        serializeStudentObject();
    }

    private static void serializeStudentObject() {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Student student = createStudent();
        String jsonStr = gson.toJson(student);
        System.out.println(jsonStr);
    }

    private static Student createStudent() {
        Student student = new Student();
        student.setStudentId(1000);
        student.setStudentName("Ramesh");
        Set < Phone > phones = new HashSet < Phone > ();
        Phone phone = new Phone();
        phone.setPhoneId(100);
        phone.setPhoneNumber("1234567890");
        phone.setPhoneType("Mobile Phone");
        phones.add(phone);

        Phone phone1 = new Phone();
        phone1.setPhoneId(101);
        phone1.setPhoneNumber("2222 3333 44");
        phone1.setPhoneType("Landline Phone");
        phones.add(phone1);

        student.setStudentPhoneNumbers(phones);
        return student;
    }
}

class Student {

    private long studentId;
    private String studentName;
    private Set < Phone > studentPhoneNumbers = new HashSet < Phone > (0);

    public long getStudentId() {
        return studentId;
    }

    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Set < Phone > getStudentPhoneNumbers() {
        return studentPhoneNumbers;
    }

    public void setStudentPhoneNumbers(Set < Phone > studentPhoneNumbers) {
        this.studentPhoneNumbers = studentPhoneNumbers;
    }

    @Override
    public String toString() {
        return "Student [studentId=" + studentId + ", studentName=" + studentName + ", studentPhoneNumbers=" +
            studentPhoneNumbers + "]";
    }

}

class Phone {

    private long phoneId;
    private String phoneType;
    private String phoneNumber;

    public Phone() {}

    public Phone(String phoneType, String phoneNumber) {
        this.phoneType = phoneType;
        this.phoneNumber = phoneNumber;
    }

    public long getPhoneId() {
        return phoneId;
    }

    public void setPhoneId(long phoneId) {
        this.phoneId = phoneId;
    }

    public String getPhoneType() {
        return phoneType;
    }

    public void setPhoneType(String phoneType) {
        this.phoneType = phoneType;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }
}

输出:

{
  "studentId": 1000,
  "studentName": "Ramesh",
  "studentPhoneNumbers": [
    {
      "phoneId": 100,
      "phoneType": "Mobile Phone",
      "phoneNumber": "1234567890"
    },
    {
      "phoneId": 101,
      "phoneType": "Landline Phone",
      "phoneNumber": "2222 3333 44"
    }
  ]
}

相关文章

微信公众号

最新文章

更多