2015-03-31 62 views
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

回答

3

我終於找到了解決方案。只需說明我的兩個子類就足夠了:

@JsonDeserialize(as = CipherRequestBean.class) 
public class CipherRequestBean extends AbstractCipherRequestBean{ 
... 
} 

@JsonDeserialize(as = CipherMultRequestBean.class) 
public class CipherMultRequestBean extends AbstractCipherRequestBean { 
private List<String> b64Data; 
... 
} 
相關問題