Skip to content

Question: Deserialize json to subtypes with complex constructor #502

@arturk9

Description

@arturk9

I am using kotlin and jackson and I am looking for a way to deserialize json with the following structure, that can vary between two cases:

Case 1:

{
    "parent1": "parentvalue1",
    "parent2": "parentvalue2",
    "child1": "childvalue1",
    "child2": "childvalue2"
}

Case 2:

{
    "parent1": "parentvalue1",
    "parent2": "parentvalue2",
    "child3": "childvalue3",
    "child4": "childvalue4"
}

My Model classes look as follows:

Parent:

open class Parent(
    val parent1: String,
    val parent2: String
) {
    constructor (parent: Parent) : this(
        parent1 = parent.parent1,
        parent2 = parent.parent2
    )
}

Children:

class Child1(
    parent: Parent,
    val child1: String,
    val child2: String
) : Parent(parent)

class Child2(
    parent: Parent,
    val child3: String,
    val child4: String
) : Parent(parent)

Is it doable to deserialize such structure using Jackson?

val parent = ObjectMapper().readValue(myJson, Parent::class.java)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions