RealmList序列化问题(Realm/Gson/Intent)

2024-01-11

我在项目中使用了 Retrofit、Gson 和 Realm。 我有这门课Example需要是Serializable。如果没有 Realm,我会这样写:

public class Example implements Serializable {
    @SerializationName("users")
    private List<String> users

    //... getters and setters
}

Realm 开始发挥作用,Example变为(请注意,出于兼容性原因,getter 和 setter 是这样的):

public class Example extends RealmObject implement Serializable {

    @SerializedName("users")
    private RealmList<RealmString> users;

    public ArrayList<String> getUsers() {
        ArrayList<String> array = new ArrayList<>();
        for (RealmString rs : users) {
            array.add(rs.getValue());
        }
        return array;
    }

    public void setUsers(ArrayList<String> users) {
        RealmList<RealmString> array = new RealmList<>();
        for (String rs : users) {
            array.add(new RealmString(rs));
        }
        this.users = array;
    }

}

RealmString 为:

public class RealmString extends RealmObject implements Serializable {

    private String val;

    //Constructors, getter and setter
}

并添加自定义 Gson 类型转换器以使其正确反序列化:

public class RealmStringRealmListConverter implements JsonSerializer<RealmList<RealmString>>,
        JsonDeserializer<RealmList<RealmString>> {

    @Override
    public JsonElement serialize(RealmList<RealmString> src, Type typeOfSrc,
                                 JsonSerializationContext context) {
        JsonArray ja = new JsonArray();
        for (RealmString tag : src) {
            ja.add(tag.getValue());
        }
        return ja;
    }

    @Override
    public RealmList<RealmString> deserialize(JsonElement json, Type typeOfT,
                                              JsonDeserializationContext context)
            throws JsonParseException {
        RealmList<RealmString> tags = new RealmList<>();
        JsonArray ja = json.getAsJsonArray();
        for (JsonElement je : ja) {
            if (je.isJsonPrimitive()) {
                tags.add(new RealmString(je.getAsString()));
            }
        }
        return tags;
    }

}

好吧,现在我们开始感觉到 Realm 开始对我们的代码产生很大的影响。但这是一个附带问题,主要问题是 Example 不再可序列化:RealmList 不再可序列化。

所以我尝试使 RealmList 成为瞬态,并使其挂起列表可以用 @Ignore 进行注释,并在序列化后重新创建 RealmList。但 Realm 不接受瞬态。

现在感觉有点卡住了Example通过我的代码的许多部分中的意图传递(它是很多类的成员)。我不想使用 id 并到处查询它。

我的问题是:

我怎样才能以允许我做的方式改变“Example”new Bundle().putSerializable("test", new Example());没有崩溃。

感谢您的帮助!


Serializable不能与RealmList,但你可以使用Parceler 库并实现 Parcelable https://realm.io/docs/java/latest/#parceler打包 RealmObjects(注意:它将把它们变成非托管副本!)

@Parcel(implementations = { UserRealmProxy.class },
        value = Parcel.Serialization.BEAN,
        analyze = { User.class })
public class User extends RealmObject {
    // ...
}

compile "org.parceler:parceler-api:1.0.3"
apt "org.parceler:parceler:1.0.3"

To 包裹RealmList,使用以下代码 https://gist.github.com/patloew/bc32a2a1a3c0097e9c7020192fb2c78f

/* Copyright 2016 Patrick Löwenstein
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

public class RealmListParcelConverter implements TypeRangeParcelConverter<RealmList<? extends RealmObject>, RealmList<? extends RealmObject>> {
  private static final int NULL = -1;

  @Override
  public void toParcel(RealmList<? extends RealmObject> input, Parcel parcel) {
    if (input == null) {
      parcel.writeInt(NULL);
    } else {
      parcel.writeInt(input.size());
      for (RealmObject item : input) {
        parcel.writeParcelable(Parcels.wrap(item), 0);
      }
    }
  }

  @Override
  public RealmList fromParcel(Parcel parcel) {
    int size = parcel.readInt();
    RealmList list = new RealmList();

    for (int i=0; i<size; i++) {
      Parcelable parcelable = parcel.readParcelable(getClass().getClassLoader());
      list.add((RealmObject) Parcels.unwrap(parcelable));
    }

    return list;
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

RealmList序列化问题(Realm/Gson/Intent) 的相关文章

随机推荐

  • 如何在 ionic 4 中刷新页面

    我想在成功删除数据后刷新页面 当我删除或更新时 我必须先刷新页面 然后刷新数据 如何在 ionic 4 中使用 navController 请帮助我 图书列表 page html
  • Blazor 角色管理通过 UI 添加角色(Crud)

    我对 blazor 还很陌生 并且对向数据库添加角色感到有些疑问 我已经实施了身份角色管理并拥有一个工作系统 但现在我想通过 GUI 添加新角色 而不是编辑数据库 我有一个名为 RolesOverview razor 的 razor 页面
  • 如何避免每个 html 页面中重复页眉和页脚代码

    我有大约十个 html 页面 每个页面也有相同的页眉和页脚标记 我可以有一个包含完整页眉和页脚的页面吗 我将从其他 html 页面引用该特定页面 如果您不关心禁用了 JavaScript 的用户 或者正在使用某些移动平台 则可以使用 Jav
  • install.packages 错误:本地存储库使用故障排除

    我刚刚创建了一个包 RTIO 和一个包存储库 Q Integrated Planning R 这是公司网络驱动器 我已将我的包放入文件夹中 Q Integrated Planning R bin windows contrib 2 15 R
  • getElementsByTagName 为 null 或未定义,仅在 IE 中 - 并且仅在函数中的一个特定位置 [重复]

    这个问题在这里已经有答案了 可能的重复 IE 中的 getElementById contentDocument 错误 https stackoverflow com questions 1477547 getelementbyid con
  • 无线电上的 Chrome 断点不会触发

    I have a page where some JavaScript modifies a radio button to be not checked and another to be checked the HTML source
  • 变量的 JavaScript 属性

    我的 JavaScript 代码有问题 我现在开始处理一些更复杂的事情 似乎在网上找到了一些答案 但不幸的是我无法解决它 问题是 我想要变量sGetMobileField and ValMob获取参数 但这样它不起作用 var oField
  • PowerShell - 将对象传递给启动作业 - 反序列化

    我知道通过 start job 执行的脚本块无法看到脚本块之外的变量 要传递变量 请使用 arguments范围 从我读过的 doco 来看 作业不能在没有连载 https learn microsoft com en us powersh
  • 不带任何特殊字符的 10 位数字的正则表达式

    10 位数字的正则表达式是什么 无特殊字符且无小数 使用此正则表达式仅匹配十位数字 d 10 要查找字符串中任意位置的十个连续数字的序列 请使用 d 10 请注意 这还将查找 11 位数字的前 10 位数字 在字符串中的任意位置搜索exac
  • 当您没有对容器的引用时,是否可以让温莎城堡解决属性依赖关系?

    我们有一个包含多个项目的解决方案 代表我们应用程序的各个层 例如 Domain Data Logic WebUI 我们的温莎城堡容器是从我们的 Web 层引用的 然后我们通过我们的层将这些依赖项级联起来 例如 In Domain publi
  • jquery 插件语法包装器

    这到底是做什么的 我知道它被 jquery 插件包围 但并没有真正理解它的作用 function undefined Plugin goes here jQuery 是一种在 javascript 中运行一段代码的方法 第一对括号是代码部分
  • php 在实例中设置匿名函数

    我刚刚开始使用 PHP 我想知道是否有一种方法可以将匿名函数添加到类实例中 例如 可以说 class A public B c new A This is where I am getting a little confused The f
  • PySpark:从数据帧创建字典的字典?

    我有以下格式的数据 这些数据是从 Hive 获取到数据帧中的 date stock price 1388534400 GOOG 50 1388534400 FB 60 1388534400 MSFT 55 1388620800 GOOG 5
  • 如何在Windows中使用批处理文件删除包含特定字符串的文件?

    我的松下相机使用其愚蠢的 PHOTOfunSTUDIO 来导入照片 它按照片拍摄日期的名称创建文件夹 并将照片分别导入到这些文件夹中 到目前为止 一切都很好 但是 如果我在从相机中删除所有旧照片之前再次导入 则无论我如何更改该软件的设置 旧
  • 将 Docker 容器与 Mesos/Marathon 链接

    到目前为止 我使用 Mesos Marathon 和 Docker 来管理服务器群以及放置在服务器上的容器 取得了巨大成功 然而 我现在想更进一步 开始做一些事情 比如自动将 haproxy 容器链接到每个启动的主 docker 服务 或者
  • SQL Server 2012 CTE 查找分层数据的根或顶层父级

    我在尝试递归地遍历层次结构以查找组织结构中可能具有的所有后代节点的顶部节点时遇到问题multiple顶级节点 我正在尝试使用 SQL Server 2012 CTE 来执行此操作 但它不会递归到达每个分支的最顶层节点 我已经尝试完全按照与此
  • 我的 Web api 2 控制器需要路由

    我有一个返回 XML 的简单 WebApi2 控制器 但我无法使用我定义的路由正确添加另一个方法 namespace CBMI WebAPIservice Controllers public class MarkersController
  • 使用 QWebEngine 渲染图像

    我正在寻找替换QWebKit with QWebEngine在我的无头渲染器中 我初始化页面load 并将一个插槽连接到loadFinished 生成最终的 PNG 图像 这曾经工作得很好WebKit但失败了QWebEngine 代码如下
  • 在 Jekyll 上的 CSS 中使用 Liquid 诱惑来调整每页的 div 背景颜色

    我正在使用 Jekyll 和 Liquidwebsite http annawees github io 我一直坚持在 CSS 中使用 Liquid 来正确编译 我尝试为每个页面的边框使用不同的颜色 并将默认设置为黑色 我很欣赏你们的任何见
  • RealmList序列化问题(Realm/Gson/Intent)

    我在项目中使用了 Retrofit Gson 和 Realm 我有这门课Example需要是Serializable 如果没有 Realm 我会这样写 public class Example implements Serializable