![](/img/trans.png)
[英]Jackson - Custom Deserializer doesn't read all the fields in JSON
[英]Custom Jackson deserializer doesn't inject into @Autowired fields
我正在嘗試將我的配置注入我的自定義StdDeserializer
。 然而問題是,即使我將 class 標記為@Component
,該字段的值也不會被注入。 注入在應用程序的其他地方沒有任何問題。
因此,我得出的結論是,問題出在反序列化器的工作方式上,因為它沒有被我們實例化,而是像下面的示例一樣:
ClassToDeserialize myClass = new ObjectMapper().readValue(mockJson, ClassToDeserialize.class);
如您所見,我的自定義反序列化器ClassToDeserializeDeserializer
沒有顯式使用,因此它使用帶有@JsonDeserialize(using = ClassToDeserialize.class)
注釋的自定義反序列化器檢測類。
@Data
@AllArgsConstructor
@SuperBuilder
@JsonDeserialize(using = MyClassDeserializer.class)
public class MyClass{
private final String field1;
private final String field2;
}
@Configuration
@ConfigurationProperties(prefix = "myconfig")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MyConfig {
private final String confField1;
private final String confField2;
}
@Component
public class MyClassDeserializer extends StdDeserializer<MyClass> {
@Autowired
MyConfig myConfig;
public MyClassDeserializer () {
this(null);
}
public MyClassDeserializer (Class<?> vc) {
super(vc);
}
@Override
public MyClassDeserializer deserialize(JsonParser parser, DeserializationContext context)
throws IOException, JsonProcessingException {
//Deserializing code that basically tries to read from myConfig
myConfig.getConfField1(); //Hello NullPointerException my old friend
}
}
MyClass myClass = new ObjectMapper().readValue(mockJson, MyClass.class);
不起作用的原因:
Jackson doesn't know anything about Spring Boot stuff, so when you readValue(..)
Jackson sees @JsonDeserialize
annotation with deserializer class and creates new instance of the deserializer (it doesn't pick up the bean, but rather just new MyClassDeserializer(..)
),這就是為什么您永遠不會看到MyConfig
被注入的原因。
如果你想讓它工作,你需要通過 Spring Boot 以某種方式注冊這個解串器,例如: How to provide a custom deserializer with Jackson and Z38008DD81C2F4D7985ECF6EZCE8 Boot
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.