問題:
在 Jackson中建立一個自訂解串器,允許在應用自訂之前存取預設反序列化器以預先填充物件
程式碼:
public class UserEventDeserializer extends StdDeserializer<User> { public UserEventDeserializer() { super(User.class); } @Override public User deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { // Line causing UnsupportedOperationException: User deserializedUser = super.deserialize(jp, ctxt, new User()); } }
解:
實作BeanDeserializerModifier為特定的物件註冊自訂反序列化器類別。
代碼:
public class UserEventDeserializer extends StdDeserializer<User> implements ResolvableDeserializer { 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; } // Required when modifying BeanDeserializer @Override public void resolve(DeserializationContext ctxt) throws JsonMappingException { ((ResolvableDeserializer) defaultDeserializer).resolve(ctxt); } public static void main(String[] args) throws Exception { 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); } }
以上是如何從自訂解串器呼叫 Jackson 的預設解串器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!