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

จะทำให้เป็นอนุกรมของฟิลด์ null โดยใช้ไลบรารี Gson ใน Java ได้อย่างไร?


โดยค่าเริ่มต้น ออบเจ็กต์ Gson จะไม่ทำให้ฟิลด์เป็นอนุกรมด้วยค่า Null เป็น JSON หากฟิลด์ในอ็อบเจ็กต์ Java เป็นโมฆะ Gson จะไม่รวมฟิลด์นั้น เราสามารถบังคับ Gson ให้เรียงลำดับค่าว่าง ผ่าน GsonBuilder ระดับ. เราต้องเรียก serializeNulls() วิธีการใน GsonBuilder ตัวอย่าง ก่อนสร้างวัตถุ Gson เมื่อ serializeNulls() ถูกเรียกว่าอินสแตนซ์ Gson ที่สร้างโดย GsonBuilder สามารถ รวมฟิลด์ว่าง ใน JSON แบบอนุกรม

ไวยากรณ์

public GsonBuilder serializeNulls()

ตัวอย่าง

import com.google.gson.*;
import com.google.gson.annotations.*;
public class NullFieldTest {
   public static void main(String args[]) {
      GsonBuilder builder = new GsonBuilder();
      builder.serializeNulls();
      Gson gson = builder.setPrettyPrinting().create();
      Employee emp = new Employee(null, 25, 40000.00);
      String jsonEmp = gson.toJson(emp);
      System.out.println(jsonEmp);
   }
}
// Employee class
class Employee {
   @Since(1.0)
   public String name;
   @Since(1.0)
   public int age;
   @Since(2.0)
   public double salary;
   public Employee(String name, int age, double salary) {
      this.name = name;
      this.age = age;
      this.salary = salary;
   }
}

ผลลัพธ์

{
   "name": null,
   "age": 25,
   "salary": 40000.0
}