0

Let's say I have the following classes:

@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.EXISTING_PROPERTY,
    property = "type",
    visible = true
)
@JsonSubTypes(
    JsonSubTypes.Type(FullXResult::class, name = "X")
)
open class BaseResult {
 
    protected val mapper: ObjectMapper = ObjectMapper()    

    var x: String = "some shared text between all subclasses"
}

open class MinimalXResult: BaseResult() {
    var y: String = "some public text specific to X"
}

class FullXResult: MinimalXResult() {
    var z: String = "some private text specific to X"

    fun asMinimal(): MinimalXResult {
        return mapper.convertValue(this, MinimalXResult::class.java)
    }

}

I want to be able to deserialize a JSON into the FullResult, and before re-serialization, cast it to a MinimalResult to the caller such that for the example classes, the properties x and y are serialized but the property z is not. @JsonIgnore is not an option here because I also want to be able to return the full result under certain conditions.

When calling asMinimal function, I get the following error:

Could not resolve type id 'X' as a subtype of `MinimalXResult`: Class `FullXResult` not subtype of `MinimalXResult`

If this type of casting can be done without Jackson, that is fine too. Thanks for any help.

Kyle Rowan
  • 87
  • 1
  • 4
  • Does this answer your question? [Java Jackson | How to serialize object specifying concrete interface](https://stackoverflow.com/questions/35527657/java-jackson-how-to-serialize-object-specifying-concrete-interface) – dnault May 27 '21 at 00:35
  • JsonViews might be another option: https://stackoverflow.com/questions/38279782/what-is-the-json-view-class-in-jackson-and-how-does-it-work – dnault May 27 '21 at 17:35

0 Answers0