如何创建通用的JsonDeserializer

杰克斯

我需要创建一个通用的反序列化器;换句话说,我不知道反序列化的目标类是什么。

我在互联网上看到了一些示例,这些示例由它们创建一个反序列化器,例如JsonDeserializer<Customer>,然后最后返回a new Customer(...)问题是我不知道返回类是什么。

我想我将需要使用反射来创建类的实例并填充字段。我如何通过反序列化方法来做到这一点?

public class JsonApiDeserializer extends JsonDeserializer<Object> {

    @Override
    public Object deserialize(JsonParser jp, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {

        //Need to parse the JSON and return a new instance here
    }

}
匹克男孩

经过一些测试,我发现@jax的答案有问题。

正如@Staxman指出的那样,createContextual()在反序列化器的构造过程中会调用它,而不是在反序列化的每个过程中都会被调用。返回的反序列化器createContextual将由Jackson库缓存。因此,如果您的解串器使用的类型不止一种(例如,公共父级的子类型),它将抛出类型不匹配异常,因为targetClass属性将是Jackson库缓存的最后一个类型。

正确的解决方案应该是:

public class JsonApiDeserializer extends JsonDeserializer<Object> implements
        ContextualDeserializer {

    private Class<?> targetClass;

    public JsonApiDeserializer() {
    }

    public JsonApiDeserializer(Class<?> targetClass) {
        this.targetClass = targetClass;
    }

    @Override
    public Object deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        Object clazz = targetClass.newInstance();
        //Now I have an instance of the annotated class I can populate the fields via reflection
        return clazz;
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt,
            BeanProperty property) throws JsonMappingException {
        //gets the class type of the annotated class
        targetClass = ctxt.getContextualType().getRawClass();
        //this new JsonApiDeserializer will be cached
        return new JsonApiDeserializer(targetClass);
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章