![](/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.