我遇到了自定义JsonDeserializer的问题。我尝试使用抽象类的不同实现,具体取决于Rest服务调用收到的JSON消息(如果数据是Array
则使用一个,如果它是sa String
使用另一个):
@Path("/rest/cipher")
public interface CipherManager {
@POST
@Consumes("application/json")
@Produces("application/json")
@Path("/encrypt")
public Response cipher(AbstractCipherRequestBean jsonRequestData);
}
反序列化器看起来像这样:
public class CipherRequestDeserializer extends JsonDeserializer<AbstractCipherRequestBean> {
@Override
public AbstractCipherRequestBean deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectMapper mapper = (ObjectMapper) jp.getCodec();
ObjectNode root = (ObjectNode) mapper.readTree(jp);
Class<? extends AbstractCipherRequestBean> abstractCipherRequestBeanClass = null;
Iterator<Entry<String, JsonNode>> elementsIterator = root.getFields();
while (elementsIterator.hasNext()) {
Entry<String, JsonNode> element = elementsIterator.next();
String name = element.getKey();
if(name.equals("b64Data")){
if(element.getValue().isArray()){
abstractCipherRequestBeanClass = CipherMultRequestBean.class;
}else{
abstractCipherRequestBeanClass = CipherRequestBean.class;
}
}
}
if (abstractCipherRequestBeanClass == null){
return null;
}
return mapper.readValue(root, abstractCipherRequestBeanClass);
}
}
继承如下:
public class RequestBean {
protected String b64Data;
...
}
@JsonDeserialize(using = CipherRequestDeserializer.class)
public abstract class AbstractCipherRequestBean extends RequestBean{
...
}
public class CipherRequestBean extends AbstractCipherRequestBean{
...
}
public class CipherMultRequestBean extends AbstractCipherRequestBean {
private List<String> b64Data;
...
}
我相信,由于两个实现都继承了@JsonDeserialize
注释,因此每次调用mapper.readValue(root, abstractCipherRequestBeanClass)
都会再次调用deserialize
方法,以StackOverflowError结束。
有没有办法避免这种情况?由于最后我使用实际课程调用mapper
,我认为它使用的是默认mapper
实现,而不是CipherRequestDeserializer
实现。
答案 0 :(得分:4)
我终于找到了解决方案。只是注释我的两个子类就足够了:
@JsonDeserialize(as = CipherRequestBean.class)
public class CipherRequestBean extends AbstractCipherRequestBean{
...
}
@JsonDeserialize(as = CipherMultRequestBean.class)
public class CipherMultRequestBean extends AbstractCipherRequestBean {
private List<String> b64Data;
...
}