gpt4 book ai didi

android - WorkManager Data.Builder 不支持 Parcelable

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:52:58 25 4
gpt4 key购买 nike

当您有一个包含大量变量( bool 值、整数、字符串)的大型 POJO 并且您想要使用新的工作管理器来启 Action 业时。然后您创建一个数据文件,该文件被添加到一次性工作请求对象中。

构建此数据文件的最佳做法是什么? (编写 100 行代码只是说为每个变量在构建器上放置 int 感觉是错误的。)

回答

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

    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 的原因是数据是持久化的。

不确定 Data not supporting parcelable 的详细答案是什么?

- This answer解释其:

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.

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

最佳答案

super 简单 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;
}

关于android - WorkManager Data.Builder 不支持 Parcelable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50798329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com