首页 > 解决方案 > 如何将字符串数组转换为房间实体对象,即 kolin 中的 DAO?

问题描述

我有这样的回应:

    {
  "response":{"numFound":5303,"start":0,"maxScore":6.5102634,"docs":[
      {
        "id":"10.1371/journal.pone.0000290",
        "journal":"PLoS ONE",
        "eissn":"1932-6203",
        "publication_date":"2007-03-14T00:00:00Z",
        "article_type":"Research Article",
        "author_display":["Rayna I. Kraeva",
          "Dragomir B. Krastev",
          "Assen Roguev",
          "Anna Ivanova",
          "Marina N. Nedelcheva-Veleva",
          "Stoyno S. Stoynov"],
        "abstract":["Nucleic acids, due to their structural and chemical properties, can form double-stranded secondary structures that assist the transfer of genetic information and can modulate gene expression. However, the nucleotide sequence alone is insufficient in explaining phenomena like intron-exon recognition during RNA processing. This raises the question whether nucleic acids are endowed with other attributes that can contribute to their biological functions. In this work, we present a calculation of thermodynamic stability of DNA/DNA and mRNA/DNA duplexes across the genomes of four species in the genus Saccharomyces by nearest-neighbor method. The results show that coding regions are more thermodynamically stable than introns, 3′-untranslated regions and intergenic sequences. Furthermore, open reading frames have more stable sense mRNA/DNA duplexes than the potential antisense duplexes, a property that can aid gene discovery. The lower stability of the DNA/DNA and mRNA/DNA duplexes of 3′-untranslated regions and the higher stability of genes correlates with increased mRNA level. These results suggest that the thermodynamic stability of DNA/DNA and mRNA/DNA duplexes affects mRNA transcription."],
        "title_display":"Stability of mRNA/DNA and DNA/DNA Duplexes Affects mRNA Transcription",
        "score":6.5102634},

现在,我想获得“抽象”字段。为此,我已将其指定为字符串,但它给了我错误,即它是数组并且无法转换为字符串。

现在我不确定如何为此创建对象,我应该指定哪种数组类型。

我检查了我们可以使用类型转换器,但不能编写相同的转换器。

以下是我尝试过的对象和转换器。

    @Entity(tableName = "news_table")
data class NewsArticles(
    @PrimaryKey var id: String = "",
    @SerializedName("article_type") var title: String? = null,
    @SerializedName("abstract") var description: Array<String>,
    @SerializedName("publication_date") var publishedAt: String? = null
)

类型转换器

    class Converters {
    @TypeConverter
    fun fromTimestamp(value: Array<String>?): String? {
        return value?.let { String(it) } //error
    }

    @TypeConverter
    fun dateToTimestamp(array: Array<String>): String? {
        return array.toString()
    }
}

它给了我返回行的错误,即不能使用提供的参数调用以下函数。

编辑 :

现在我将定义更改为 ArrayList @SerializedName("abstract") var description: ArrayList,

并转换为此

    class ArrayConverters {
    @TypeConverter
    fun fromArray(value: ArrayList<String>?): String? {
        return value?.let { arrayToString(it) }
    }

    @TypeConverter
    fun arrayToString(array: ArrayList<String>): String? {
        return array.toString()
    }
}

现在它显示此错误:错误:多个方法定义相同的转换。与这些冲突:CustomTypeConverter

请帮忙。谢谢你。

编辑2:

根据 Richard slond 的回答,我已将转换器添加为

class ArrayConverters {
    @TypeConverter
    fun to(array: Array<String>): String {
        return array.joinToString(" ")
    }

    @TypeConverter
    fun from(value: String): List<String> {
        return value.split(" ")
    }
}

并在数据库中添加为

@Database(entities = [NewsArticles::class], version = 2, exportSchema = false)
@TypeConverters(ArrayConverters::class)
abstract class AppDatabase : RoomDatabase() {

    abstract fun newsArticlesDao(): NewsArticlesDao
}

也在新闻文章模块中

    @Entity(tableName = "news_table")
@TypeConverters(ArrayConverters::class)
data class NewsArticles(
    @PrimaryKey var id: String = "",
    @SerializedName("article_type") var title: String? = null,
    @SerializedName("abstract") var description: String? = null,
    @SerializedName("publication_date") var publishedAt: String? = null
)

如果我添加了字符串,这里的描述变量会出现错误,因为该字段以数组开头。

如果我指定为arraylist,它会给出错误,因为无法将此类型添加到数据库中,请尝试使用类型转换器。

少了什么东西??

标签: androidkotlinandroid-roomdaotypeconverter

解决方案


如果你真的想这样做,你需要找到一种方法来使用原始类型来表示字符串数组。最简单的方法是使用 JSON 格式。因此,在您的转换器中,您需要对字符串数组进行序列化和反序列化。

作为快速解决方案(我不推荐)如下:

    @TypeConverter
    fun to(array: Array<String>): String {
        return array.joinToString(",")
    }

    @TypeConverter
    fun from(value:String):  Array<String> {
        return value.split(",")
    }

请注意,按照此路径,您的字符串不能包含逗号 - 但您可以使用另一个不太常见的字符作为分隔符


推荐阅读