Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธี import Gson library ใน JShell Java 9

JShell ของ Java 9 รองรับการ import library ภายนอกผ่าน classpath ใช้ Gson สำหรับ serialize/deserialize JSON

ขั้นตอน

  1. ตั้งค่า classpath: /env --class-path C:\path\to\gson.jar
  2. Import package: import com.google.gson.*
  3. ตรวจสอบด้วย /import

ตัวอย่างการใช้งาน

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

jshell> import com.google.gson.*
jshell> /import
| import java.io.*
| import com.google.gson.*
...

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

jshell> class Employee {
   private String firstName, lastName, designation, location;
   public Employee(String fn, String ln, String desig, String loc) {
       this.firstName = fn; this.lastName = ln; 
       this.designation = desig; this.location = loc;
   }
   // getters และ toString()...
}
| created class Employee

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

jshell> String json = g.toJson(e)
json ==> "{\n  \"firstName\": \"Jai\",\n  \"lastName\": \"Adithya\",\n  \"designation\": \"Content Developer\",\n  \"location\": \"Hyderabad\"\n}"

jshell> Employee e1 = g.fromJson(json, Employee.class)
e1 ==> Name = Jai, Adithya | Job designation = Content Developer | location = Hyderabad.