I a working on a custom JsonSerializer & JsonDeserializer I want to serialize json (ints) to enums and deserialize enums to ints
I have created an interface for this purpose, where the enums have a function called fromValue which should take the deserialized value and return the enum:
interface EnumSerializationInterface {
val value: Int
fun fromValue(value: Int): EnumSerializationInterface?
}
example enum:
enum class TestDummyEnumTestEnum(override val value: Int):
EnumSerializationInterface {
ENUM1(1),
ENUM2(2);
override fun fromValue(value: Int): EnumSerializationInterface? {
for (enum in TestDummyEnumTestEnum.values()) {
if (enum.value == value) {
return enum
}
}
return null
}
}
My serializer works but i am having trouble deserializing, my serializer & deserializer:
class EnumDeserializer: JsonDeserializer<EnumSerializationInterface> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?): EnumSerializationInterface {
val value = json.asInt()
return typeOfT.fromValue(value)
/*THIS DOES NOT WORK*/
}
}
class EnumSerializer: JsonSerializer<EnumSerializationInterface> {
override fun serialize(src: EnumSerializationInterface?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
return context!!.serialize(src!!.value)
}
}
My issue is that i cannot get the 'fromValue' function from typeOfT.
Does anybody know how to get the actual typeOfT?