Home > Mobile >  Convert string with separator to data class instance
Convert string with separator to data class instance

Time:04-30

I have a string separated by ";" like this:

var dataString: String = "Juan;25;Argentina"

And I want to convert it to this sample data class:

data class Person (
var name: String? = "",
var age: Int? = "",
var location: String? = "")

The only way I figured out to that is like this:

var dataString: String = "Juan;25;Argentina"
var fieldList = dataString.split(";").map { it.trim() }
var personItem = Person(fieldList[0], fieldList[1], fieldList[2])

But this is too static, if I then have to add new field to Person data class, I have to manually add fieldList[3]

Which is the most efficient way to do this? (I searched a lot, but couldn't find it :S )

SOLUTION:

//Data in string
val rawData = "name;age;location\nPerson1;20;USA\nPerson2;30;Germany" 

//Custom string reader with ";" separator
val customCSV = csvReader { delimiter = ';' }

//String to map list
val parsed = csvReader().readAllWithHeader(rawData)

//Mal list to list of <Person>
val finalData = grass<Person>().harvest(parsed)
for (entry in entryList) {
   //entry is an instance of Person
}

EDIT2: You can obtain field names for header line like this:

var headerLine = ""
for (entry in Person::class.members) {
   if (member.name.isNotEmpty())
       headerLine  = ";${member.name}"
}
headerLine.substring(1)

CodePudding user response:

The string you showed here looks like a CSV dataset. So I think you could use kotlin-grass and kotlin-csv

https://github.com/blackmo18/kotlin-grass https://github.com/doyaaaaaken/kotlin-csv/

Example:

val rawData = "Person1;20;USA/nPerson1;30;Germany"

val parsed = csvReader().readAllWithHeader(rawData)
val finalData = grass<Person>().harvest(parsed)

  • Related