在Jackson 中,自定義反序列化器允許擴展或修改預設反序列化行為。常見的需求是在應用自訂邏輯之前存取預設反序列化器以部分反序列化物件。但是,直接從自訂反序列化器中呼叫 deserialize 會導致堆疊溢位異常。
要解決此問題,可以實作 BeanDeserializerModifier 並使用 SimpleModule 註冊。此修飾符可以在反序列化器建立過程中進行幹預,並將預設反序列化器注入到我們自訂的反序列化器中。
以下程式碼示範如何實作此目的:
import com.fasterxml.jackson.databind.BeanDescription; import com.fasterxml.jackson.databind.JsonDeserializer; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.module.BeanDeserializerModifier; import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.util.StdDeserializer; public class UserEventDeserializer extends StdDeserializer<User> implements ResolvableDeserializer { private static final long serialVersionUID = 7923585097068641765L; private final JsonDeserializer<?> defaultDeserializer; public UserEventDeserializer(JsonDeserializer<?> defaultDeserializer) { super(User.class); this.defaultDeserializer = defaultDeserializer; } @Override public User deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { User deserializedUser = (User) defaultDeserializer.deserialize(jp, ctxt); // Special logic return deserializedUser; } // for some reason you have to implement ResolvableDeserializer when modifying BeanDeserializer // otherwise deserializing throws JsonMappingException?? @Override public void resolve(DeserializationContext ctxt) throws JsonMappingException { ((ResolvableDeserializer) defaultDeserializer).resolve(ctxt); } public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException { SimpleModule module = new SimpleModule(); module.setDeserializerModifier(new BeanDeserializerModifier() { @Override public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) { if (beanDesc.getBeanClass() == User.class) return new UserEventDeserializer(deserializer); return deserializer; } }); ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(module); User user = mapper.readValue(new File("test.json"), User.class); } }
透過向ObjectMapper 註冊此模組,可以啟用User 類別的自訂反序列化,從而允許存取預設的反序列化器用於在應用自訂邏輯之前預先填充物件。
以上是如何存取自訂 Jackson 解串器中的預設解串器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!