Vadim
Vadim

Reputation: 825

How to serialize a simple scala class to a CSV file?

I have a simple scala class with more than 150 fields and use Scala 2.11.

I want to convert instances to csv and write to the file system. I found several libs but all them for Scala case classes. I cant use case classes because of Scala restrictions.

Could you recommend to me the way to get csv from class without using the field name in method toCsv.

class ToCsv (
   field1: String,
   field2: String,
    ...
) {
 def toCsv(): String = s"$field1 $field2 …"
}

Tried to use

com.fasterxml.jackson.dataformat.csv

  val mapper = new CsvMapper
  val schema = mapper
    .schemaFor(classOf[Test.FiveMinuteUser])
    .withoutHeader
    .withColumnSeparator('\t')

But got empty string

Upvotes: 1

Views: 305

Answers (1)

Costin Chiulan
Costin Chiulan

Reputation: 31

If anyone encounter this issue, this is how it worked for me.

//@JsonPropertyOrder(Array("firstFieldHeaderNameInCsv", "secondFieldHeaderNameInCsv")) // important!
// ^^^ without annotation properties ordered alphabetically
class Test {

  @JsonProperty("firstFieldHeaderNameInCsv")
  var field1: String = _

  @JsonProperty("secondFieldHeaderNameInCsv")
  var field2: String = _
}


object Runner extends App {

  val testInstance = new Test()
  testInstance.field1 = "myValue"
  testInstance.field2 = "myOtherValue"

  val mapper = new CsvMapper()

  mapper
    .writerFor(classOf[Array[Test]])
    .`with`(mapper.schemaFor(classOf[Test]).withHeader())
    .writeValue(new File("/path/to/file.csv"), Array(testInstance))

}

Output in /path/to/file.csv

"firstFieldHeaderNameInCsv","secondFieldHeaderNameInCsv"
myValue,myOtherValue

More details can be found in this post https://cowtowncoder.medium.com/writing-csv-with-jackson-204fdb3c9dac

Upvotes: 1

Related Questions