gpt4 book ai didi

java - 使用 JSON 注释更改返回类型

转载 作者:太空宇宙 更新时间:2023-11-04 12:14:58 25 4
gpt4 key购买 nike

我有以下 hibernate 类

@Entity
class A {
List<String> list;

...

List<String> getList();
}

在 hibernate 实例化和 Jackson 序列化之后,getList()方法序列化为org.hibernate.collection.internal.PersistentBag 。在反序列化期间,我收到以下异常:com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection, could not initialize proxy...

如果我要替换 org....PersistentBag 中的序列化字符串(使用简单的 String.replaceAll...)到 java....List类型,对象会根据需要很好地反序列化。

hibernate的PersistentSet和java的HashSet也是如此。

知道如何在不替换字符串的情况下解决这个问题吗?

最佳答案

对于序列化为 PersistentSetSet,我也遇到了同样的问题。

我使用 Mixin 和 Set 的自定义反序列化器解决了这个问题,将 PersistentSet 反序列化为 HashSet

同样的方法应该适用于 List - PersistentBag

设置混合:

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonDeserialize(using = SetDeserializer.class)
public abstract class SetMixin {

@JsonCreator
public SetMixin(Set<?> s) {
}
}

设置反序列化器:

public class SetDeserializer extends JsonDeserializer<Set> {

@Override
public Set deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
ObjectMapper mapper = (ObjectMapper) jp.getCodec();
JsonNode node = mapper.readTree(jp);
Set<Object> resultSet = new HashSet<>();
if (node != null) {
if (node instanceof ArrayNode) {
ArrayNode arrayNode = (ArrayNode) node;
Iterator<JsonNode> nodeIterator = arrayNode.iterator();
while (nodeIterator.hasNext()) {
JsonNode elementNode = nodeIterator.next();
resultSet.add(mapper.readValue(elementNode.toString(), Object.class));
}
} else {
resultSet.add(mapper.readValue(node.toString(), Object.class));
}
}
return resultSet;
}
}

将 SetMixin 添加到 ObjectMapper:

mapper.addMixIn(Set.class, SetMixin.class);

关于java - 使用 JSON 注释更改返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39507125/

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