如何在scala中将任何数据类型的数组转换为逗号分隔的字符串

问题描述

我当前的代码是:

schema.fields.foreach(f => {
                              if (f.dataType.typeName == "array") {
                                throw ArrayDataTypeNotSupportedException(s"${f.name} column is ArrayType," +
                                  "writing arrays to CSV isn't supported. Please convert this column to a different data type.")
                              }
                            })

当前,我们不支持csv中的数组,但现在希望通过将其转换为字符串来支持任何数据类型的数组。字符串应以逗号分隔。

测试用例:

test("testArrayInSchema") {
    val df = spark.createDataFrame(Seq(
      TestDataSetArrays(
        Array(1,2,3),Array("a","b","c"),Array(new Timestamp(0),new Timestamp(1),new Timestamp(3))
      )
    ))
    assertThrows[ArrayDataTypeNotSupportedException] {
            writeDataFrame(df)

    }

现在我们需要删除此异常,因为我们需要通过将数组转换为字符串来支持数组

解决方法

要将数组转换为逗号分隔的字符串,可以使用mkString(“,”)方法 例如:

 val arr = Array("test1","test2")
 arr.mkString(",")