Java 类的Jackson反序列化程序<;?扩展Foo>;
我想要一个用于类文本的序列化器和反序列化器。它应该从/映射到JSON字符串。它还应该与泛型类一起工作 我尝试编写自定义反序列化程序,但它处理所有类,而不仅仅是我想要的类:Java 类的Jackson反序列化程序<;?扩展Foo>;,java,serialization,jackson,deserialization,Java,Serialization,Jackson,Deserialization,我想要一个用于类文本的序列化器和反序列化器。它应该从/映射到JSON字符串。它还应该与泛型类一起工作 我尝试编写自定义反序列化程序,但它处理所有类,而不仅仅是我想要的类: public class MyDeserializer extends JsonDeserializer<Class<? extends Foo>> { public Class<? extends Foo> deserialize(JsonParser jp, Deserializ
public class MyDeserializer extends JsonDeserializer<Class<? extends Foo>> {
public Class<? extends Foo> deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
String token = jp.getText();
switch(token) {
case "FOO": return Foo.class;
case "BAR": return Bar.class;
}
return null;
}
}
JSON:
ObjectMapper用法:
MyPOJO pojo = new MyPOJO();
pojo.fooType = Foo.class;
ObjectMapper om = new ObjectMapper();
String json = om.writeValueAsString(pojo);
您试图实现的目标似乎是不可能的,因为在运行时,您的类
MyDeserializer
被视为JsonDeserializer
,而您的字段FootType
只是类型class
而不是类型class
在您的情况下,最好的解决方案是注释类型为
classe的字段。您是否可以为Json POJO添加代码并使用ObjectMapper
?添加一些代码如果您不想使用@JsonDeserialize,您能否仅在需要的地方使用@JsonIgnore?(即瞬态&不可串行化)@Shine:no。如果它不是类的类型,我应该可以使用jsonderializer
{
"fooType": "FOO"
}
MyPOJO pojo = new MyPOJO();
pojo.fooType = Foo.class;
ObjectMapper om = new ObjectMapper();
String json = om.writeValueAsString(pojo);
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule("MyModule")
.addDeserializer(Class.class, new MyDeserializer());
mapper.registerModule(module);
public class MyDeserializer extends JsonDeserializer<Class<?>> {
// The default deserializer for a property of type Class
private final FromStringDeserializer.Std defaultDeserializer;
public MyDeserializer() {
// Set the default deserializer
this.defaultDeserializer = FromStringDeserializer.findDeserializer(Class.class);
}
public Class<?> deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
// Check whether we should used the custom or default deserializer
// based on the bean class
if (accept(jp.getCurrentValue().getClass())) {
// The custom deserializer
String token = jp.getText();
switch(token) {
case "FOO": return Foo.class;
case "BAR": return Bar.class;
}
return null;
}
// Call the default deserializer
return (Class<?>) defaultDeserializer.deserialize(jp, ctxt);
}
// Returns true if this bean class has fields of type Class that must
// be deserialized with the custom deserializer, false otherwise
public boolean accept(Class<?> beanClass) {
// Implement your logic here
// You could for example have all the bean classes in a Set and
// check that the provided class is in the Set
}
}