栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/636688.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号