Skip to content

Latest commit

 

History

History
115 lines (92 loc) · 6.39 KB

README.md

File metadata and controls

115 lines (92 loc) · 6.39 KB

Kotlin Serialization CSV

Maven Central Snapshot CI Status Codecov License

Library to easily use Kotlin Serialization to serialize/parse CSV.

All types of record classes are supported (primitives, classes, enums, nested classes, ...). However, CSV serialization works best if the column number if fixed. So, collections (lists, sets, maps) and open classes should be avoided.

Gradle Dependencies

// Kotlin Serialization CSV
implementation("de.brudaswen.kotlinx.serialization:kotlinx-serialization-csv:0.1.0")

// Kotlin Serialization is added automatically, but can be added to force a specific version
implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.14.0")

Usage

First configure your project according to the documentation of the Kotlin Serialization library.

CSV Example

@Serializable
data class Person(val nickname: String, val name: String?, val appearance: Appearance)

@Serializable
data class Appearance(val gender: Gender?, val age: Int?, val height: Double?)

@Serializable
enum class Gender { MALE, FEMALE }

fun main() {
    val csv = Csv(CsvConfiguration(hasHeaderRecord = true))

    val records = listOf(
        Person("Neo", "Thomas A. Anderson", Appearance(Gender.MALE, 37, 1.86)),
        Person("Trinity", null, Appearance(Gender.FEMALE, null, 1.74))
    )
    val serialized = csv.stringify(Person.serializer().list, records)
    println(serialized)
    // nickname,name,appearance.gender,appearance.age,appearance.height
    // Neo,Thomas A. Anderson,MALE,37,1.86
    // Trinity,,FEMALE,,1.74

    val input = """
        nickname,appearance.gender,appearance.height,appearance.age,name
        Neo,MALE,1.86,37,Thomas A. Anderson
        Trinity,FEMALE,1.74,,
    """.trimIndent().replace("\n", "\r\n")
    val parsed = csv.parse(Person.serializer().list, input)
    println(parsed)
    // [
    //   Person(nickname=Neo, name=Thomas A. Anderson, appearance=Appearance(gender=MALE, age=37, height=1.86)),
    //   Person(nickname=Trinity, name=null, appearance=Appearance(gender=FEMALE, age=null, height=1.74))
    // ]
}

Pre-defined CSV formats

The library comes with multiple pre-defined formats that can be used out of the box.

Config Description
default Standard Comma Separated Value format, as for rfc4180 but allowing empty lines. Format is unstable and may change in upcoming versions.
rfc4180 Comma separated format as defined by RFC 4180.
excel Excel file format (using a comma as the value delimiter).

Configuration

CSV serialization and parsing options can be changed by providing a custom CsvConfiguration.

Option Default Value Description
delimiter , The delimiter character between columns.
recordSeparator \r\n The record separator.
quoteChar " The quote character used to quote column values.
quoteMode MINIMAL The quote mode used to decide if a column value should get quoted.
  • ALL: Quotes all fields.
  • ALL_NON_NULL: Quotes all non-null fields and fields which contain special characters.
  • ALL_NON_NUMERIC: Quotes all non-numeric fields and fields which contain special characters.
  • MINIMAL: Quotes fields which contain special characters.
  • NONE: Never quotes fields (requires CsvConfiguration.escapeChar to be set).
escapeChar null (\\ for QuoteMode.NONE) The escape character used to escape reserved characters in a column value.
nullString empty string The value to identify null values.
unitString Unit The value to identify Unit values.
ignoreEmptyLines true Ignore empty lines during parsing.
hasHeaderRecord false First line is header record.
headerSeparator . Character that is used to separate hierarchical header names.
hasTrailingDelimiter false If records end with a trailing delimiter.

Requirements

Dependency Versions
Kotlin Serialization 0.14.0

License

Copyright 2020 Sven Obser

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.