首頁 > 軟體

如何將Java物件轉換為JSON範例詳解

2022-08-11 22:00:54

要將 Java 物件或 POJO (普通舊 Java 物件)轉換為 JSON,我們可以使用JSONObject將物件作為引數的建構函式之一。在下面的範例中,我們將StudentPOJO 轉換為 JSON 字串。Student類必須提供 getter 方法,JSONObject通過呼叫這些方法建立 JSON 字串。

在此程式碼段中,我們執行以下操作:

  • 使用 setter 方法建立Student物件並設定其屬性。
  • 建立JSONObject呼叫object並將Student物件用作其建構函式的引數。
  • JSONObject使用 getter 方法生成 JSON 字串。
  • 呼叫object.toString()方法獲取 JSON 字串。
 
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.json.JSONObject;
 
import java.util.Arrays;
 
public class PojoToJSON {
 
    public static void main(String[] args) throws JsonProcessingException {
        Student student = new Student();
        student.setId(1L);
        student.setName("Alice");
        student.setAge(20);
        student.setCourses(Arrays.asList("Engineering", "Finance", "Chemistry"));
 
        JSONObject object = new JSONObject(student);
        String json = object.toString();
        System.out.println(json);
        System.out.println(new Gson().toJson(student));
        // Creating Object of ObjectMapper define in Jackson API
        ObjectMapper Obj = new ObjectMapper();
 
        // Converting the Java object into a JSON string
        String jsonStr = Obj.writeValueAsString(student);
        // Displaying Java object into a JSON string
        System.out.println(jsonStr);
 
    }
}

執行此程式碼會產生以下結果:

{"courses":["Engineering","Finance","Chemistry"],"name":"Alice","id":1,"age":20}
{"id":1,"name":"Alice","age":20,"courses":["Engineering","Finance","Chemistry"]}
{"id":1,"name":"Alice","age":20,"courses":["Engineering","Finance","Chemistry"]}

上面程式碼中使用的Student類:

 
import java.util.List;
 
public class Student {
 
    private Long id;
    private String name;
    private int age;
    private List<String> courses;
 
    public Student(Long id, String name, int age, List<String> courses) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.courses = courses;
    }
 
    Student() {
 
    }
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getAge() {
        return age;
    }
 
    public void setAge(int age) {
        this.age = age;
    }
 
    public List<String> getCourses() {
        return courses;
    }
 
    public void setCourses(List<String> courses) {
        this.courses = courses;
    }
 
}

Maven 依賴項

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example.javaobjectjson</groupId>
    <artifactId>JavaObjectJSON</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
 
        <!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20211205</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.9.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.1</version>
        </dependency>  
    </dependencies>
    </project>

總結

到此這篇關於如何將Java物件轉換為JSON的文章就介紹到這了,更多相關Java物件轉換JSON內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com