This `Converter.toJson` implementation works, but ...
# klaxon
k
This
Converter.toJson
implementation works, but it feels like I'm doing something wrong. Should I be creating additional
Klaxon()
instances inside
toString
and specifying converters for nested fields there?
d
Why do you need that converter in the first place? Usually Klaxon and Kotlin are smart enough with type inference? How do KeyboardLayoutSpec and KeyboardLayoutRow look? The json doesn't conform do their structure (which is when you usually need a converter, or possibly when using generics)?
k
in this case, the serialization format involves an array with first element
metadata
that is different from all the following
rows
d
Maybe try a sealed class? I think I remember that it works.. I'm just not sure about the Array generics though.
Usually the practice of non-uniform json is not so great though... if you control this, you could use a JsonObect as the root and have
data class(val firstRow: ...., val layout: Array<...>)
k
I'm coding to an outside spec, can't change the document schema
d
Oh well, maybe the sealed class though?
k
so declare
class KeyboardLayoutSpec: List<SealedClassOfMetadataOrRow>
? I could try that. Haven't yet because it doesn't present a real great picture of things on the Kotlin side. Having its users see it as a sequence that begins with the metadata element would be mostly not good.
d
That's non-standard json for you, I also don't like such things (I would maybe convert it to what I mentioned before after the parsing)... At worst, I wouldn't create a new Klaxon instance inside the toJson, but rather pass it in to the converter.
Otherwise you'd get a new instance for each json value...
Once apon a time, I had the same problem and wanted to get the raw json into a property so that I could convert it at a second step...