【发布时间】:2019-08-23 01:09:11
【问题描述】:
我需要反序列化一个长而复杂的 json,为此我编写了一组 java 类来映射数据,并且我必须为许多不同类型的字段编写自定义反序列化器(包括 String、Boolean、BigDecimal、等)。
我知道我可以使用相应的自定义反序列化器(如下所示)注释 java 类中的所有字段,但是我需要注释所有类中的几乎所有字段。
@JsonDeserialize(using = CustomBooleanJsonDeserializer.class)
private boolean active;
我也知道我可以在 Spring 默认 ObjectMapper 中注册一个模块(如 here),但我只想为这些特定的类使用这些自定义反序列化器。
@Bean
public Module customDeserializersModule() {
SimpleModule module = new SimpleModule();
module.addDeserializer(Boolean.class, new CustomBooleanJsonDeserializer());
// add other custom deserializers
return module;
}
我什至知道我可以在RestController中使用自定义的ObjectMapper,但是我不想放弃通过@RequestBody自动绑定数据的便利,因为我必须防止别人在没有的情况下使用它必要的自定义反序列化程序。
@RequestMapping(method = RequestMethod.POST, value = "/data")
public ResponseEntity<ServerInfo> register(@RequestBody DataMapper data) {
// DataMapper is the target POJO class of the json's deserialization
}
简而言之,我正在寻找类似的课程级别:
@JsonDeserialize(using = CustomStringJsonDeserializer.class, forType = String.class)
@JsonDeserialize(using = CustomBooleanJsonDeserializer.class, forType = Boolean.class)
@JsonDeserialize(using = CustomBigDecimalJsonDeserializer.class, forType = BigDecimal.class)
public class DataMapper implements Serializable {
// obviously, @JsonDeserialize doesn't have a forType method
}
或者可能以某种方式为DataMapper 类实现自定义反序列化器,它定义了如何根据其数据类型反序列化每个字段(无需注释每个字段):
@JsonDeserialize(using = DataMapperJsonDeserializer.class)
public class DataMapper implements Serializable {
// How can I implement the DataMapperJsonDeserializer with these
// characteristics? I know about the ContextualDeserializer interface,
// but I don't know how to use it without annotating each field.
}
或某种方式将模块的效果限制在一个包或一组类中:
module.restrictedTo(/*some package or set of classes*/);
// com.fasterxml.jackson.databind.Module doesn't have a restrictedTo method
【问题讨论】:
标签: java json spring jackson deserialization