gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:11:00 25 4
gpt4 key购买 nike

我在使用自定义 JsonDeserializer 时遇到问题。我正在尝试根据 Rest 服务调用收到的 JSON 消息使用抽象类的不同实现(如果数据是 Array 使用一个,如果它是 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一个。

最佳答案

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

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

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

关于java - 使用继承的自定义 JsonDeserializer 导致 StackOverflowError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29371384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com