Java 9 引入了一個互動式REPL 命令列工具,名稱為JShell。它允許我們執行Java程式碼片段並立即獲得結果。我們可以導入可以從JShell會話中存取的外部類,透過類路徑。 Gson庫是一個Java序列化/反序列化庫,用於將Java物件轉換為JSON,反之亦然。
在下面的程式碼片段中,我們可以在JShell中設定類別路徑
<strong>jshell> /env --class-path C:\Users\User\gson.jar | Setting new options and restoring state.</strong>
一旦我們在JShell中導入了 gson 庫 ,就能在清單中看到該庫。
<strong>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:{}}</strong>
在下面的程式碼片段中,我們建立了一個Employee 類別。
<strong>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}"</strong>
在下面的程式碼片段中,我們可以建立一個Employee 物件的實例並顯示結果。
<strong>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.</strong>
以上是在Java 9的JShell中如何導入gson函式庫?的詳細內容。更多資訊請關注PHP中文網其他相關文章!