gpt4 book ai didi

java - GSON:如何在保持循环引用的同时防止 StackOverflowError?

转载 作者:搜寻专家 更新时间:2023-10-30 21:45:22 26 4
gpt4 key购买 nike

我有一个带有循环引用的结构。出于调试目的,我想转储它。基本上与任何格式一样,但我选择了 JSON。

因为可以是任何类,所以我选择了不需要JAXB注解的GSON。

但是 GSON 会遇到循环引用并递归直到 StackOverflowError

我怎样才能限制 GSON

  • 忽略某些类(class)成员?@XmlTransient@JsonIgnore 都不遵守。

  • 忽略某些对象图路径?例如。我可以指示 GSON 不要序列化 ​​release.customFields.product

  • 到最多 2 层的深度?

相关:Gson.toJson gives StackOverFlowError, how to get proper json in this case? (public static class)

最佳答案

只需将字段设为 transient (如 private transient int field = 4;)。 GSON 明白这一点。

编辑

不需要内置注解; Gson 允许您插入自己的策略来排除字段和类。它们不能基于路径或嵌套级别,但可以使用注释和名称。

如果我想跳过类“my.model.Person”中名为“lastName”的字段,我可以编写这样的排除策略:

class MyExclusionStrategy implements ExclusionStrategy {

public boolean shouldSkipField(FieldAttributes fa) {
String className = fa.getDeclaringClass().getName();
String fieldName = fa.getName();
return
className.equals("my.model.Person")
&& fieldName.equals("lastName");
}

@Override
public boolean shouldSkipClass(Class<?> type) {
// never skips any class
return false;
}
}

我也可以做我自己的注释:

@Retention(RetentionPolicy.RUNTIME)
public @interface GsonRepellent {

}

并将shouldSkipField方法重写为:

public boolean shouldSkipField(FieldAttributes fa) {
return fa.getAnnotation(GsonRepellent.class) != null;
}

这将使我能够执行以下操作:

public class Person {
@GsonRepellent
private String lastName = "Troscianko";

// ...

要使用自定义 ExclusionStrategy,请使用构建器构建 Gson 对象:

Gson g = new GsonBuilder()
.setExclusionStrategies(new MyOwnExclusionStrategy())
.create();

关于java - GSON:如何在保持循环引用的同时防止 StackOverflowError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14489463/

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