Help to parse this file #103
Replies: 2 comments 1 reply
-
The XML example isn't 100% well-formed, but I assume that it is just an error. There are some challenges here, including value dependent types. The way to resolve such must include a custom serializer. I would advise Then it is up to normal code to translate the list of attributes to a regular resource, and the other way around. Unfortunately formats The advantage of the chosen approach is that the DTO can remain private (you may need to fiddle a bit with the way it is private) and encapsulated, but going this way is generally easier and more maintainable than actually writing a fully custom serializer (rather than a delegating one). I would go something like (please note, I didn't try to compile it so there may be some small errors in it): @Serializable(with=Resource.Companion::class)
@Serialname("resource")
class Resource constructor(/*...*/) {
private constructor(orig: ResourceDTO)
@Serializable
@Serialname("resource")
private class ResourceDTO(val data: List<ValueDTO>) {
constructor(orig: Resource): this(TODO("Some way to get the data out of the resource")
}
companion object : KSerializer<Resource> {
override fun deserialize(decoder: Decoder): Resource {
Resource(ResourceDTO.serializer().deserialize(strategy))
}
override fun serializeserialize(encoder: Encoder, value: Resource) {
ResourceDTO.serializer().serialize(encoder, ResourceDTO(value))
}
}
}
@Serializable
private sealed class ValueDTO
@Serializable
@Serialname("str")
private class StrValueDTO(
@XmlElement(false) val name:String,
@XmlValue(true) val value: String
)
@Serializable
@Serialname("date")
private class DateValueDTO(
@XmlElement(false) val name:String,
@XmlValue(true) val value: String // Could be some datetime value with an appropriate serializer (as long as it serializes to some string value not struct).
) |
Beta Was this translation helpful? Give feedback.
-
Oh thank you so much! I would try it. |
Beta Was this translation helpful? Give feedback.
-
Hi
I need to parse this file. I am new user of serialization in XML and I don't know if i need to use a special annotation.
I will appreciate any help
A response class have a item resouces (with name and a list of resouce)
My problem is how to parse str with name and values
Thank you for the help
Beta Was this translation helpful? Give feedback.
All reactions