Pihentagy
06/28/2024, 10:10 AM@JsonSubTypes
by hand, of is there a convenient solution to use the class name?
So how to avoid
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(
JsonSubTypes.Type(value=MyState1::class, name = "MyState1"),
// ...
// ...
JsonSubTypes.Type(value= MyState99::class, name = "MyState99")
)
abstract class AbstractState
Btw I don't need the class at all, I am just logging to a jsonb field, and will query it directly from db.
So say, I have this hierarchy:
abstract class AbstractState
data class MyState(val text: String)
and all my wish is to put
{
"text": "the text value"
}
to a jsonb field.thanksforallthefish
07/02/2024, 6:13 AMval objectMapper: ObjectMapper by lazy {
JsonMapper.builder()
.findAndAddModules()
.addModules(
SimpleModule()
.addDesers<Any>(CustomAbstractStateDeerializer())
.addSers(CustomAbstractStateSerializer())
.build()
}
private fun <T> SimpleModule.addDesers(vararg desers: JsonDeserializer<*>) = apply {
desers.forEach { this.addDeserializer(it.handledType() as Class<T>, it as JsonDeserializer<out T>) }
}
private fun SimpleModule.addSers(vararg sers: JsonSerializer<*>) = apply {
sers.forEach { this.addSerializer(it) }
}
class CustomAbstractStateDeserializer : StdDeserializer<Calculation>(AbstractState::class.java) {
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): AbstractState {
// play around here to convert from json to code, this code sample will NOT work
return p.codec.readValue(p, AbstractState::class.java)
}
}
class CustomAbstractStateSerializer : StdSerializer<AbstractState>(AbstractState::class.java) {
override fun serialize(value: AbstractState, gen: JsonGenerator, provider: SerializerProvider) {
gen.writeStartObject()
//play around here to generate you custom json, eg:
when (value) {
is MyState -> gen.writeObjectField("text", value.text)
}
gen.writeEndObject()
}
}
Pihentagy
07/02/2024, 3:13 PMobjectMapper.writeValueAsString(myAbstractState)