使用继承的自定义JsonDeserializer导致StackOverflowError

时间:2015-03-31 14:41:02

标签: java json annotations jackson json-deserialization

我遇到了自定义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实现。

1 个答案:

答案 0 :(得分:4)

我终于找到了解决方案。只是注释我的两个子类就足够了:

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

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