Hi there! I am running into a Jackson issue with sealed classes. I have the following code: ```@Js...
a
Hi there! I am running into a Jackson issue with sealed classes. I have the following code:
Copy code
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
sealed class Principal
object AnonymousUser : Principal() {
  val _empty: String? = null
}

// other implementations of Principal

fun main() {
  // jacksonObjectMapper() is a function in jackson which creates an object mapper with the Kotlin module
  val input = jacksonObjectMapper().writeValueAsString(AnonymousUser)
  val principal = jacksonObjectMapper().readValue(input, Principal::class.java)
  println(principal)
}
This gives me the following error:
Copy code
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "_empty" (class com.example.hellojavabin.graphql.context.Principal$AnonymousUser), not marked as ignorable (0 known properties: ])
 at [Source: (String)"{"@type":"Principal$AnonymousUser","_empty":null}"; line: 1, column: 49] (through reference chain: com.example.hellojavabin.graphql.context.Principal$AnonymousUser["_empty"])
What am I missing here? I also tried casting the input string directly to
AnonymousUser
but that fails with the same issue. Has anyone done something similar?
Seems I had to put in
Copy code
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME)
@JsonSubTypes(
  JsonSubTypes.Type(Principal.AnonymousUser::class, name = "anonymousUser"),
)
However, this only works when I have
AnonymousUser
as a regular class or dataclass. This does not work when
AnonymousUser
is a singleton aka object. Any ideas?
655 Views