如何在 Java 9 中的 JShell 中导入 gson 库?\

javaobject oriented programmingprogramming更新于 2025/9/26 13:00:17

Java 9  引入了一个名为 JShell 的交互式 REPL 命令行工具。它允许我们执行 Java 代码片段并立即获得结果。我们可以导入可以通过类路径从 JShell 会话访问的外部类。Gson 库 是一个 Java 序列化/反序列化库,用于将 Java 对象转换为 JSON  以及反之亦然。

在下面的代码片段中,我们可以在 JShell 中设置类路径

jshell> /env --class-path C:\Users\User\gson.jar |设置新选项并恢复状态。

一旦我们在 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.

相关文章


有用资源