如何在 Java 9 的 JShell 中匯入 Gson 庫?\n


Java 9 推出了一款名為JShell的互動式REPL命令列工具。它允許我們執行 Java 程式碼段並獲得直接的結果。我們可以匯入可透過類路徑從 JShell 會話訪問的外部類。Gson 庫是一個 Java 序列化/反序列化庫,旨在將Java 物件轉換為JSON 以及反之亦然。

在以下程式碼段中,我們可以在 JShell 中設定類路徑

jshell> /env --class-path C:\Users\User\gson.jar
| Setting new options and restoring state.


一旦在 JShell 中匯入了gson 庫 ,就能夠在列表中看到該庫。

jshell> import com.google.gson.*

jshell> /import
| import java.io.*
| import java.math.*
| import java.net.*
| import java.nio.file.*
| import java.util.*
| import java.util.concurrent.*
| import java.util.function.*
| import java.util.prefs.*
| import java.util.regex.*
| import java.util.stream.*
| import com.google.gson.*

jshell> Gson g = new GsonBuilder().setPrettyPrinting().create()
g ==> {serializeNulls:false,factories:[Factory[typeHier ... 78b9],instanceCreators:{}}


在以下程式碼段中,我們建立了一個Employee 類。

jshell> class Employee {
...>       private String firstName;
...>       private String lastName;
...>       private String designation;
...>       private String location;
...>       public Employee(String firstName, String lastName, String desigation, String location) {
...>          this.firstName = firstName;
...>          this.lastName = lastName;
...>          this.designation = designation;
...>          this.location = location;
...>       }
...>       public String getFirstName() {
...>          return firstName;
...>       }
...>       public String getLastName() {
...>          return lastName;
...>       }
...>       public String getJobDesignation() {
...>          return designation;
...>       }
...>       public String getLocation() {
...>          return location;
...>       }
...>       public String toString() {
...>          return "Name = " + firstName + ", " + lastName + " | " +
...>                 "Job designation = " + designation + " | " +
...>                 "location = " + location + ".";
...>       }
...>    }
| created class Employee

jshell> Employee e = new Employee("Jai", "Adithya", "Content Developer", "Hyderabad");
e ==> Name = Jai, Adithya | Job designation = Content D ... er | location = Hyderabad.

jshell> String empSerialized = g.toJson(e)
empSerialized ==> "{\n \"firstName\": \"Jai\",\n \"lastName\": \" ... ation\": \"Hyderabad\"\n}"


在以下程式碼段中,我們可以建立Employee 物件的例項並顯示結果。

jshell> System.out.println(empSerialized)
{
   "firstName": "Jai",
   "lastName": "Adithya",
   "designation": "Content Developer",
   "location": "Hyderabad"
}
jshell> Employee e1 = g.fromJson(empSerialized, Employee.class)
e1 ==> Name = Jai, Adithya | Job designation = Content D ... er | location = Hyderabad.

更新於: 2020-04-02

298 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.