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

GSON:如何在保持循环引用的同时防止StackOverflowError?,第1张

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

只需将字段设为瞬态(如中的

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();


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5642520.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存