首頁 >Java >java教程 >如何在Java中使用@JsonSerialize註解實作自訂序列化器?

如何在Java中使用@JsonSerialize註解實作自訂序列化器?

WBOY
WBOY轉載
2023-09-11 18:17:06803瀏覽

如何在Java中使用@JsonSerialize註解實作自訂序列化器?

@JsonSerialize 註解用於在欄位序列化期間宣告自訂序列化程式。我們可以透過擴充StdSeralizer類別來實作自訂序列化器。並且需要重寫StdSerializer類別的serialize()方法。

語法

@Target(value={ANNOTATION_TYPE,METHOD,FIELD,TYPE,PARAMETER})
@Retention(value=RUNTIME)
public @interface JsonSerialize

在下面的程式中,我們可以使用@JsonSerialize註解來實作自訂的序列化器

範例

#
import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.*;
import com.fasterxml.jackson.databind.ser.std.*;
public class JsonSerializeAnnotationTest {
   public static void main (String[] args) throws JsonProcessingException, IOException {
      Employee emp = new Employee(115, "Adithya", new String[] {"Java", "Python", "Scala"});
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
      System.out.println(jsonString);
   }
}
// CustomSerializer class
class CustomSerializer extends StdSerializer {
   public CustomSerializer(Class t) {
      super(t);
   }
   public CustomSerializer() {
      this(Employee.class);
   }
   @Override
   public void serialize(Employee emp, JsonGenerator jgen, SerializerProvider sp) throws IOException, JsonGenerationException {
      StringBuilder sb = new StringBuilder();
      jgen.writeStartObject();
      jgen.writeNumberField("id", emp.getId());
      jgen.writeStringField("name", emp.getName());
      for(String s: emp.getLanguages()) {
         sb.append(s).append(";");
      }
      jgen.writeStringField("languages", sb.toString());
      jgen.writeEndObject();
   }
}
// Employee class
@JsonSerialize(using=CustomSerializer.class)<strong>
</strong>class Employee {
   private int id;
   private String name;
   private String[] languages;
   public Employee(int id, String name, String[] languages) {
      this.id = id;
      this.name = name;
      this.languages = languages;
   }
   public int getId() {
      return this.id;
   }
   public String getName() {
      return this.name;
   }
   public String[] getLanguages() {
      return this.languages;
   }
<strong>   </strong>@Override<strong>
 </strong>  public String toString() {
      StringBuilder sb = new StringBuilder("ID: ").append(this.id).append("\nName: ").append(this.name).append("\nLanguages:");
      for(String s: this.languages) {
         sb.append(" ").append(s);
      }
      return sb.toString();
   }
}

輸出

{
   "id" : 115,
   "name" : "Adithya",
   "languages" : "Java;Python;Scala;"
}
#

以上是如何在Java中使用@JsonSerialize註解實作自訂序列化器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除