android - 如何使用 GSON 模型处理 Android 中的 OrmLite ForeignCollection 字段

标签 android ormlite foreign-collection

所以,我有一些最初由 GSON 填充的 OrmLite 4.41 模型类(为清楚起见进行了简化)

public class Crag {
  @DatabaseField(id=true) private int id;
  @ForeignCollectionField(eager=true, maxEagerLevel=2) @SerializedName("CragLocations")
  private Collection<CragLocation> cragLocations;
}

public class CragLocation {
    @DatabaseField(id=true) private int id;
    @DatabaseField private int locationType;
    @DatabaseField(foreign=true, foreignAutoCreate=true, foreignAutoRefresh=true)
    private Crag crag;  
    @DatabaseField(foreign=true, foreignAutoCreate=true, foreignAutoRefresh=true)
    private Location location;
}

public class Location {
    @DatabaseField(id=true) private int id;
    @DatabaseField private BigDecimal latitude;
    @DatabaseField private BigDecimal longitude;
}

然后我正在测试事情是否如我所料发生...

@Test
public void canFindById() {
    Crag expected = ObjectMother.getCrag431();
    _repo.createOrUpdate(template431);
    Crag actual = _repo.getCragById(431);
    assertThat(actual, equalTo(template431));
}

而且它们不相等……为什么不呢?因为在 GSON 创建的对象中(ObjectMother.getCrag431()),Crag 的 cragLocations 字段是一个 ArrayList,而在由 OrmLite 加载的对象中,它是一个 EagerForeignCollection

我是不是漏掉了什么技巧?有没有办法告诉 OrmLite 我想要那个 Collection 是什么类型?我是否应该只使用一种方法将集合作为数组列表返回并测试其是否相等?

提前致谢

最佳答案

Is there a way to tell OrmLite what type I want that Collection to be?

没有办法做到这一点。当 ORMLite 返回您的 Crag 时,它要么是 EagerForeignCollection 要么是 LazyForeignCollection

Should I just have a method that returns the collection as an arraylist and test for equality on that?

我假设在您的 Crag.equals(...) 方法中,您正在测试 cragLocations 字段的相等性,如 this.cragLocations.equals( other.cragLocations)。这是行不通的,因为正如您猜测的那样,它们是不同的类型。

如果您需要测试相等性,您可以将它们提取为一个数组。像这样的东西:

Array.equals(
    this.cragLocations.toArray(new CragLocation[this.cragLocations.size()]),
    other.cragLocations.toArray(new CragLocation[this.cragLocations.size()]));

关于android - 如何使用 GSON 模型处理 Android 中的 OrmLite ForeignCollection 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12343293/

相关文章:

java - 域类中的 ForeignCollection 初始化

android - 在 Column 中包装一个 listviewBuilder?

android - 如何查找Android后台运行的服务是什么?

android - 使用包含 ENUM_INTEGER 和 DATE_TIME 数据类型的 Ormlite 在 SQLite 中插入行

java - ORMLite 外国 Collection

java - 数据库中不存在外部集合字段

java - 将字符串发送到服务器,不带反斜杠

具有固定后缀的 Android EditText

android - ORMLite 处理 uniqueCombo 约束失败异常

android - 如何将 ORMLite 与 android 集成