【问题标题】:Realm with Gson alternative to ExclusionStrategy and custom typeadapters使用 Gson 替代 ExclusionStrategy 和自定义类型适配器的领域
【发布时间】:2017-02-21 18:55:42
【问题描述】:

所以,我说使用Realm 并在将它与Gson 结合时遇到了这个已知的issue。 我开始看到一些奇怪的序列化输出,它们破坏了我的 Rest API 的逻辑。

我发现设置ExclusionStrategy 并为我的每个模型编写自定义序列化程序可以解决这个问题。看到这个link

但我有 20 多个模型,未来更有可能改变。因此,坚持这种解决方法意味着我每次更改模型时都必须更改序列化程序,这似乎打破了我认为通过同时使用 RealmGson 可以实现的简单性。

我的问题是:是否有其他已知的解决方法可以绕过这些限制?还是这是我唯一的选择?

【问题讨论】:

  • 请注意,ExclusionStrategy 仅在旧版本的 Realm 上是必需的。如果您使用最新版本 (2.3.1),则不再需要它。

标签: android gson realm


【解决方案1】:

是的。使用 ExclusionStrategy,并在将其传递给 GSON 之前使用 realm.copyFromRealm(managedRealmObject);

    ExclusionStrategy exclusionStrategy = new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getDeclaringClass().equals(RealmObject.class);
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    };

    Gson gson = new GsonBuilder()
            .setExclusionStrategies(exclusionStrategy)
            .create();

    String json = gson.toJson(realm.copyFromRealm(myObject));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    相关资源
    最近更新 更多