1
我遇到了自定義JsonDeserializer的問題。我試圖使用依賴於通過REST服務調用收到的JSON消息的抽象類的不同實現(如果數據是Array
使用一個,如果它是一個String
使用另一個):使用繼承的自定義JsonDeserializer導致StackOverflowError
解串器看起來是這樣的:
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
。