Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách import thư viện gson vào JShell trong Java 9


Java 9 giới thiệu công cụ dòng lệnh REPL tương tác tên là JShell. Nó cho phép thực thi các đoạn mã Java và nhận kết quả ngay lập tức. Chúng ta có thể import các lớp bên ngoài có thể truy cập từ phiên JShell thông qua classpath. Thư viện Gson là thư viện Java serialization/deserialization dùng để chuyển đổi Java Objects thành JSON và ngược lại.

Trong đoạn mã dưới đây, chúng ta thiết lập classpath trong JShell:

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

Sau khi import gson library trong JShell, có thể thấy thư viện đó trong danh sách.

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:{}}

Trong đoạn mã dưới đây, chúng ta tạo lớp 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\": \"Adithya\",\n \"designation\": \"Content Developer\",\n \"location\": \"Hyderabad\"\n}"

Trong đoạn mã dưới đây, chúng ta tạo instance của đối tượng Employee và hiển thị kết quả.

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.