【问题标题】:How to convert String array to the room entity object i.e DAO in kolin?如何将字符串数组转换为房间实体对象,即 kolin 中的 DAO?
【发布时间】:2020-11-13 16:55:09
【问题描述】:

我有这样的回应:

    {
  "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") 变量描述: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,它会给出错误,因为无法将此类型添加到数据库中,请尝试使用类型转换器。

缺少什么??

【问题讨论】:

    标签: android kotlin android-room dao typeconverter


    【解决方案1】:

    Collection(如ArrayList)数据存储到数据库中的最简单方法是将它们转换为StringJSON格式和GSON库(由 Google 开发)专为这种情况而设计。

    如何使用:

    String jsonString;
    
    toJsonButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Gson gson = new Gson();
    
            jsonString = gson.toJson(student);                  //object -> json
        }
    });
    
    toObjectButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Gson gson = new Gson();
    
            Student currentStudent = gson.fromJson(jsonString, Student.class);  //json -> object
        }
    });
    

    • 提醒:尝试将您的Collection 放入Object(作为成员变量),否则您可能需要进行以下额外工作:

    获取Collection 的类型:

    TypeToken<List<Integer>> typeToken = new TypeToken<List<Integer>>(){};
    
    List<Integer> retrievedNumbers = gson.fromJson(numbersJsonString, typeToken.getType());
    

    【讨论】:

      【解决方案2】:

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

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

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

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

      【讨论】:

      • 嗨@richard soland,请检查我尝试使用您的解决方案但仍有错误的编辑。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-07
      • 2020-07-15
      • 2011-12-27
      • 2023-03-28
      • 2013-01-01
      • 2021-07-23
      相关资源
      最近更新 更多