Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
458 views
in Technique[技术] by (71.8m points)

kotlin how to parse text into a list of data class

I have a kotlin data class described as:

data class Credentials(val p: String, val id: String, val key: String, val pass: String, val out: String)

I am trying to read from 2 text files located in a directory, and put them into this data class.

How the data looks:

config file

[user1]
out = specialk
id = mike

[user2]
out = specialk
id = mike

[user3]
out = specialk
id = mike

credentials file

[user1]
key = qwer1
pass = 3452

[user2]
key = qwer3
pass = 345232

[user3]
key = qwer5
pass = 3452gfd

Setting it up:

val homepath = System.getProperty("user.home")
val config = "$homepath/foobar"
val cred= "$homepath/credbar"

val configStream: InputStream = File(config).inputStream()
val credStream: InputStream = File(cred).inputStream()

This next part is something I am unsure of. What I think is that I should be reading each stream and putting it into a list of data class grouped by the user. However, I'm not sure how that should be accomplished.

configStream.bufferedReader().forEachLine {
    // put to data class here. 
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I can't write single comment cause i am new at Stackowerflow. Sorry about that. If this file holds your app backup you can take backup as JSON file. This is much easier than this.

Firstly you need to add Gson dependency in your project

implementation 'com.google.code.gson:gson:2.8.6'

Secondly you need to two parser object that is for make parse to data class to JSON and JSON to data class.

You need to declare your export and import type as below

val exportType = object : TypeToken<List<Credentials>>() {}.type

And after that for convert your data to JSON String you can use this

private fun List<Credentials>.toJson() = Gson().toJson(this, exportType)

this code returns String.

and if you want to convert JSON to String you can use this code

private fun fromJson(str: String): List<Credentials> {
    return try {
        Gson().fromJson(str, exportType)
    } catch (e: Exception) {
        Log.e("From Json Exception", "$e")
        emptyList()
    }
}

this code returns list of your data class.

I hope this can help you. I did not ask is this you want to do because my Stacowerflow account is new.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...