I had a list of objects and saved them as a String in shared preferences. Now I need to extract that saved string and convert it back to the list of objects. So how to convert this kind of string
[DataClass(label=testLabel, testData=someData), DataClass(label=testLabel, testData=someData)]
To val result = listOf<DataClass>()
So as result I will be able to get data from dataclass.label
and dataclass.testData
CodePudding user response:
I would recommend to go with @BenP's and @cactustictacs suggestions in the comments below your question.
val str = "[DataClass(label=testLabel, testData=someData), DataClass(label=testLabel, testData=someData)]"
data class DataClass(
val label: String,
val testData: String
)
val result = str
.removeSurrounding("[DataClass(label=", ")]")
.split(", testData=", "), DataClass(label=")
.chunked(2)
.map { DataClass(it[0], it[1]) }
result.forEach(::println)
CodePudding user response:
As all other comments and answer recommend you to use a serialization
library instead of manually converting string
to the object
, because it would be more idiomatic, less error-prone, and easier to maintain.
You can use Kotlin-Serialization
for this. To enable it, perform these three steps
Add kotlin-serialization
plugin to dependencies
of your project-level build.gradle
dependencies {
//..
classpath "org.jetbrains.kotlin:kotlin-serialization:$kotlin_version"
//..
}
Apply plugin in your module-level build.gradle
apply plugin: "kotlinx-serialization"
Add Json
encoder dependency to module's build.gradle
dependencies {
implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:2.0.1"
}
To serialize
your data class
annotate it with @Serializable
@Serializable
data class DataClass{
val label: String,
val testData: String
}
Now to convert list of DataClass
to String
just use encodeToString
method of Json
class.
val dataClassList = listOf(DataClass("dfd", "fdf"), DataClass("dfd", "fdf"), DataClass("dfd", "fdf"))
val jsonString = Json.encodeToString(dataClassList)
Save jsonString
to shared preferences
To convert it back to the list of DataClass
use decodeFromString
of Json
class.
val decodedDataClassList = Json.decodeFromString<List<DataClass>>(jsonString)
CodePudding user response:
I would recommend you to use Gson, instead of calling toString() as already mention, there's no fromString() method.
private fun DataClassToJson(data: Data): String {
val gson = GsonBuilder().create()
return gson.toJson(data)
}
// save the string to preferences and retrieve it
private fun jsonToDataClass(data: String): Data {
val dataType = object : TypeToken<Data>() {}.type
// convert string back to object
return Gson().fromJson(data, dataType)
}