首页 > 解决方案 > Firestore中的序列化/反序列化模型

问题描述

我有以下课程要存储在 Firestore 中。

public class User extends Model {

    @PropertyName("user_auth_id")
    public String authUid;

    @PropertyName("first_name")
    public String firstName;

    @PropertyName("last_name")
    public String lastName;

    @PropertyName("picture_url")
    public String pictureUrl;

    @PropertyName("email")
    public String email;

    @PropertyName("companies")
    public ArrayList<UserCompany> companies;

    public User() {}
}

public class UserCompany extends Model {

public String name;
public String role;
public String position;

public UserCompany() {
    super();
}

public UserCompany(Company company, String role, String position) {
    this();
    name = company.name;
    this.role = role;
    this.position = position;
}

public Map<String, Object> toObject() {
    Map<String, Object> object = new HashMap<>();
    object.put("id", id);
    object.put("name", name);
    object.put("role", role);
    object.put("position", position);
    return object;
}
}

@IgnoreExtraProperties
public class Model {
@Exclude
public String id;

public <T extends Model> T withId(@NonNull final String id) {
    this.id = id;
    return (T) this;
}
}

我想使用一个事务来更新一个用户条目,它是新创建的公司列表。(appUser instanceOf User)

transaction.update(userRef, "companies", appUser.companies);

如果我这样做......我得到

无效数据。不支持的类型:ro.exemple.model.UserCompany

我怎样才能序列化一个用户对象,以便我可以反序列化它

User appUser = queryDocumentSnapshots.getDocuments().get(0).toObject(User.class);

其中 queryDocumentSnapshots 是我的 firestore 数据库中的查询结果。

我知道我可以从 ArrayList 更改为 HashMap,但我希望保留 List,并尝试对其进行序列化和反序列化,以便在 firestore 中获取对象数组。

标签: androidfirebaseserializationdeserializationgoogle-cloud-firestore

解决方案


如果这个序列化你必须将你的类标记为可序列化..

public UserCompany extends Model implements Serializable
public class User extends Model implements Serializable

加上标签类Model以及


推荐阅读