gpt4 book ai didi

java - 向 Jackson 反序列化器添加自定义参数

转载 作者:行者123 更新时间:2023-12-04 07:37:33 27 4
gpt4 key购买 nike

我有一个自定义反序列化器。但我希望能够传递额外的参数。例如

@JsonDeserialize(using=CustomDeserializer.class, customParm=value)
MyObject obj;

如何在注解上传入我的自定义参数?

最佳答案

您不能将自己的参数添加到 @JsonDeserialize,因为你不能改变 Jackson 对这个注解的实现。

但是,您可以通过稍微不同的方式实现您的目标。您可以发明自己的注解(我们称之为 @MyAnnotation)并将其与您的属性上的 @JsonDeserialize 注释一起使用:

@JsonDeserialize(using = CustomDeserializer.class)
@MyAnnotation(customParm = "value")
private MyObject obj;

注解的实现非常简单。以下示例注释只定义了一个 String 参数。

@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {

String customParm();
}

然后就可以从内部访问@MyAnnotation的参数了你的反序列化器如下。

  • 像往常一样,你的反序列化器需要实现 deserialize 方法您在其中进行属性的实际反序列化。

  • 除了你的反序列化器需要实现ContextualDeserializer interface并实现 createContextual method .在这里您配置您的反序列化器(通过从 @MyAnnotation 获取 customParm)。Jackson 会在实际反序列化之前调用此方法。

public class CustomDeserializer extends StdDeserializer<MyObject> implements ContextualDeserializer {

private String customParm = null;

public CustomDeserializer() {
super(MyObject.class);
}

public CustomDeserializer(String customParm) {
super(MyObject.class);
this.customParm = customParm;
}

@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property)
throws JsonMappingException {
MyAnnotation myAnnotation = property.getAnnotation(MyAnnotation.class);
if (myAnnotation != null) {
String customParm = myAnnotation.customParm();
// return a new instance, so that different properties will not share the same deserializer instance
return new CustomDeserializer(customParm);
}
return this;
}

@Override
public MyObject deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// do your deserialization (using customParm)
return ...;
}
}

关于java - 向 Jackson 反序列化器添加自定义参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67664374/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com