-
I have the following YAML structure: ---
- - :permit
- MIT
- :who: stranger
:why:
:versions: []
:when: 2023-07-27 07:50:57.411184000 Z
- - :permit
- Apache 2.0
- :who: stranger
:why:
:versions: []
:when: 2023-07-27 07:51:14.222256000 Z This is the license file from the LicenseFinder project. If I get it correctly, this YAML is basically a We tried different things to create our own Serializer, but the closest what we got is this one: val fromString = Yaml.default.decodeFromString(
ListSerializer(
LicenseEntrySerializer()
),
File("/path/to/the/license_finder_decisions.yml").readText(),
)
class LicenseEntrySerializer: KSerializer<List<String>> {
override val descriptor: SerialDescriptor = ListSerializer(String.serializer()).descriptor
override fun deserialize(decoder: Decoder): List<String> {
val input = decoder.beginStructure(descriptor)
input.decodeElementIndex(descriptor)
val decision = input.decodeStringElement(descriptor, 0)
input.decodeElementIndex(descriptor)
val name = input.decodeStringElement(descriptor, 1)
input.endStructure(descriptor)
return listOf(decision, name)
}
override fun serialize(encoder: Encoder, value: List<String>) {
// We don't need it yet
}
} We basically just asssume that the order of the YAML is stable, parsing the first two String (which are important for us), and ignoring the object. However, I don't see any good solution (yet) to return an "nice Object" instead. Can someone help here? In best case the serializer return something like this data class License(
val decision: String
val name: String
val info: Info
)
data class Info(
val who: String,
val why: String,
val versions: List<String>,
val when: Instant // Or some other Date type 🙃
) So basically the I appreciate any help. Update:By the way, the library throws the following error in case I use "an Object" (the
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You're on the right track the idea to use a custom serializer - kotlinx.serialization won't support this unusual structure out of the box.
You'll need to change the signature of the custom serializer to return a -class LicenseEntrySerializer: KSerializer<List<String>> {
+class LicenseEntrySerializer: KSerializer<License> { And then adjust the implementation of You should be able to use kotlinx.serialization's default serializer for the data class Info(
@SerialName(":who") val who: String,
@SerialName(":why") val why: String,
@SerialName(":versions") val versions: List<String>,
@SerialName(":when") val when: Instant // Or some other Date type 🙃
) Hope that helps! |
Beta Was this translation helpful? Give feedback.
Thanks for the reply @charleskorn!
That pushed us into the right direction I guess.
We finally managed to have a nice
License
object that contains aInfo
object 🥳We just have to a "second"
SerialDescriptor
to theLicenseEntrySerializer
that is able to deserialize theInfo
object: