WorkManager Data.Builder不支持Parcelable [英] WorkManager Data.Builder does not support Parcelable

查看:72
本文介绍了WorkManager Data.Builder不支持Parcelable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您的POJO很大,并带有大量的变量(布尔值,整数,字符串),并且您想使用新的工作管理器来开始工作时.然后,您创建一个数据文件,该文件将添加到一次性工作请求对象中.

When you have a big POJO with loads of variables (Booleans, Int, Strings) and you want to use the new Work Manager to start a job. You then create a Data file which gets added to the one time work request object.

构建此数据文件的最佳实践是什么?(写100行代码只是对每个变量说要把int放在构建器上,这是错误的.)

What would be the best practices to build this data file? (It feels wrong to be writing 100 lines of code to just say put int on the builder for every variable.)

我最终分解了我的可包裹对象,因为我认为这是最好的实现.我不想使用gson lib,因为它会向我的对象添加另一层序列化.

I ended up breaking apart my parcelable object as i thought this was the best implementation. I did not want to use gson lib as it would of added another layer of serialization to my object.

    Data.Builder builder = new Data.Builder();
        builder.putBoolean(KEY_BOOL_1, stateObject.bool1);
        builder.putBoolean(KEY_BOOL_2, stateObject.bool2);
        builder.putBoolean(KEY_BOOL_3, stateObject.bool3);
        builder.putInt(KEY_INT_1, stateObject.int1);
        builder.putInt(KEY_INT_2, stateObject.int2);
        builder.putString(KEY_STRING_1, stateObject.string1);
        return builder.build();

更新

我的问题的部分答案是@CommonsWare指出的:

不支持Parcelable的原因是数据被保留.

不确定不支持可打包数据的详细答案是什么?

-此答案解释了其:

Not sure what the detailed answer to Data not supporting parcelable?

- This answer explains its :

数据是一个轻量级的容器,它是一个简单的键值映射并且只能保存基本&的值字符串及其字符串版本.确实是为了轻而易举的中间转移数据.它不应该用于并且不能持有可序列化或可打包的对象.

The Data is a lightweight container which is a simple key-value map and can only hold values of primitive & Strings along with their String version. It is really meant for light, intermediate transfer of data. It shouldn't be use for and is not capable of holding Serializable or Parcelable objects.

请注意,序列化时数据大小限制为10KB.

Do note, the size of data is limited to 10KB when serialized.

推荐答案

使用 GSON 超级简单: https://stackoverflow.com/a/28392599/5931191

// Serialize a single object.    
public String serializeToJson(MyClass myClass) {
    Gson gson = new Gson();
    String j = gson.toJson(myClass);
    return j;
}
// Deserialize to single object.
public MyClass deserializeFromJson(String jsonString) {
    Gson gson = new Gson();
    MyClass myClass = gson.fromJson(jsonString, MyClass.class);
    return myClass;
}

这篇关于WorkManager Data.Builder不支持Parcelable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆