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

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

王林
王林轉載
2023-08-25 19:29:051319瀏覽

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

@JsonDeserialize 註解用於將 JSON 反序列化為 Java 物件時宣告自訂反序列化器。我們可以透過使用泛型類型Employee 擴充功能StdDeserializer  類別來實作自訂反序列化器,並且需要重寫deserialize() 方法StdDeserializer 類別。

語法

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

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

範例

import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.annotation.*;
import com.fasterxml.jackson.databind.deser.std.*;
public class JsonDeSerializeAnnotationTest {
   public static void main (String[] args) throws JsonProcessingException, IOException {
      Employee emp = new Employee(115, "Adithya");
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writeValueAsString(emp);
      emp = mapper.readValue(jsonString, Employee.class);
      System.out.println(emp);
   }
}
// CustomDeserializer class
class CustomDeserializer extends StdDeserializer<Employee> {
   public CustomDeserializer(Class<Employee> t) {
      super(t);
   }
   public CustomDeserializer() {
      this(Employee.class);
   }
   @Override
   public Employee deserialize(JsonParser jp, DeserializationContext dc) throws IOException, JsonProcessingException {
      int id = 0;
      String name = null;
      JsonToken currentToken = null;
      while((currentToken = jp.nextValue()) != null) {
         switch(currentToken) {
            case VALUE_NUMBER_INT:
            if(jp.getCurrentName().equals("id")) {
               id = jp.getIntValue();
            }
            break;
            case VALUE_STRING:
            switch(jp.getCurrentName()) {
               case "name":
               name = jp.getText();
               break;
               default:
               break;
            }
            break;
            default:
            break;
         }
      }
      return new Employee(id, name);
   }
}
// Employee class
@JsonDeserialize(using=CustomDeserializer.class)<strong>
</strong>class Employee {
   private int id;
   private String name;
   public Employee(int id, String name) {
      this.id = id;
      this.name = name;
   }
   public int getId() {
      return id;
   }
   public String getName() {
      return name;
   }
   @Override
   public String toString() {
      StringBuilder sb = new StringBuilder("ID: ").append(this.id).append("\nName: ").append(this.name);
      return sb.toString();
   }
}

輸出

ID: 115
Name: Adithya

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

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