Struggling to deserialize an array of tables #342
-
EDIT: maybe i should ask rather, how would one go about this initially, ignoring my code below, how would i take in a list of files and their attributes, serialize and then deserialize them ORIGINAL: The goal of part of my project is to take the files in a given directory, store some information about them (name, path, size; for example), into toml, then later deserialize that so it can use that information. im struggling with the deserialization bit of the project. so to serialize the basic rundown is: object Index {
// basic index file configuration
@Serializable
data class Main(
val files: MutableList<Files>,
)
@Serializable
data class Files(
val file: String,
val hash: String,
val metafile: Boolean,
)
}
fun createOrUpdateIndex(environment: String) {
val indexArray: MutableList<Index.Files> = ArrayList()
if (File("index.toml").exists()) {
File("index.toml").delete()
}
File(".").walk().forEach {
if (it.isFile) {
val fileName = Path("./").relativize(it.toPath()).toString()
// hash
val hash = sha256(it)
// TODO: check if file is a metafile, and then set to true/false, for now defaults false
val metafile = false
indexArray.add(Index.Files(fileName, hash, metafile))
}
}
val serializedIndex =
Toml.encodeToString(
serializer(),
Index.Main(indexArray),
)
File("index.toml").bufferedWriter().use { out ->
out.write(serializedIndex)
}
} which leaves me with an [[files]]
file = "testfile.txt"
hash = "55b2c8e1e83905ceacc27af4d7a5587cd72b4bb04e02df8bb5e7203a9dc67f64"
metafile = false
[[files]]
file = "testfile2.txt"
hash = "b36c51f5b78dd8ffa29c0945f2cba276eefcfde340c9494ce503ac40154447f4"
metafile = false then when im trying to deserialize: fun readIndex() {
if (File("index.toml").exists()) {
val index: List<Index.Main> = TomlFileReader.decodeFromFile(serializer(), "index.toml")
index.forEach {
println(it)
}
} else {
exitProcess(0)
}
} running this last bit of code ends me up with
i feel like im having a basic misunderstanding of some fundamentals but this error is not really clicking for me on what i need to do. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
The problem is, you serialize your toml into Index.Main: val serializedIndex =
Toml.encodeToString(
serializer(),
Index.Main(indexArray),
) And then you're trying to deserialize the result to List<Index.Main>. The correct solution for you is: fun readIndex() {
if (File("index.toml").exists()) {
val index: Index.Main = TomlFileReader.decodeFromFile(serializer(), "index.toml")
index.files.forEach {
println(it)
}
} else {
exitProcess(0)
}
} |
Beta Was this translation helpful? Give feedback.
The problem is, you serialize your toml into Index.Main:
And then you're trying to deserialize the result to List<Index.Main>.
The correct solution for you is: