问题:
在 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中文网其他相关文章!