Menu

#57 Is it possible to use required header option with HeaderColumnNameTranslateMappingStrategy.

v1.0 (example)
closed
None
5
2018-06-24
2018-06-18
No

Hello,
I wolud like to use HeaderColumnNameTranslateMappingStrategy with required header column option, but it seems to be not supported yet.
(library version is 'com.opencsv:opencsv:4.2')

Is there any way to do this?

For example, this is my current code (Sorry, it's written by kotin),

fun buildDataStream(reader: Reader): CsvToBean<DataRow> {
    val strategy = HeaderColumnNameTranslateMappingStrategy<DataRow>()
    strategy.type = DataRow::class.java
    strategy.columnMapping = mapOf("identityCode" to "id", "displayName" to "name")

    return CsvToBeanBuilder<DataRow>(reader).withMappingStrategy(strategy).build()
}

data class DataRow(
    var id: Int = 1,
    var name: String = ""
)

and read csv like this.

identityCode,displayName
1,John
2,Kenta

Now, I want to change identityCode header as required header: if identityCode header is missing, CsvRequiredFieldEmptyException would be thrown.

I tried @CsvBindByName(required = true) annotation, but it seems it cannot be used with HeaderColumnNameTranslateMappingStrategy.

thanks for your help

Discussion

  • Andrew Rucker Jones

    • status: open --> closed
    • assigned_to: Andrew Rucker Jones
     
  • Andrew Rucker Jones

    HeaderColumnNameMappingStrategy is unnecessary with annotations. The name to be mapped to is the variable name in the bean you create (you would name the member variables of your bean "id" and "name"), and the name to be mapped from out of the CSV input can be specified in the "column" attribute to CsvBindByName. That's how translation works with annotations.

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.