How can I write my custom serializer to achieve t...
# serialization
e
How can I write my custom serializer to achieve the following?
Copy code
@Serializable
data class Foo(val name: String, val bar: Bar)

@Serializable
sealed class Bar
data class Bar1(val x: String) : Bar
data class Bar2(val y: Int): Bar

val foo1 = Foo("myFoo1", Bar1("Bar1"))
val foo2 = Foo("myFoo2", Bar2(2))
as JSON it should be
Copy code
"myFoo1": { "type": "bar1", "x": "Bar1" }
"myFoo2": { "type": "bar2", "y": 2 }
j
You don't need one
Slap
@SerialName("bar1")
on
Bar
and
@SerialName("bar2"
on
Bar2
and you're done
oh do you mean for
Foo
?
you can't quite make that exact transformation because names belong to the parent object. what does a type like
Copy code
@Serializable
class Enclosing(
  val one: Foo,
  val two: Foo,
)
serialize as?
e
and the list of anonymizers is the question - if possible, I'd avoid creating a separate type for every single field, but it might be the case that I'd have to
or, I just pick a different serializer lib like GSON where it's possible.
j
e
not sure how... there are multiple dynamic structure names (e.g.
PERSON
and
PHONE_NUMBER
, and there are multiple field sets that could go into that structure. for example:
Copy code
"anonymizers": {
    "PERSON": {
        "type": "redact"
    },
    "PHONE_NUMBER": {
        "type": "replace",
        "new_value": "ANONYMIZED"
    }
}
I'm not sure how this could be created dynamically
j
I see. For that I'd do a
List<Anonymizer>
and a custom serializer for the
anonymizers
property which converted the list into the map. This goes back to what I was saying about the parent object owning the name, the
anonymizers
serializer creates the parent object and thus can write names based on the child elements.
e
ahh I haven't realized that it's actually a map
🤦‍♂️
j
i have to run so if you have any other questions or more specific questions about how to do it hopefully someone else can chime in
e
I think I got it from here
🙏
fwiw the final structure looks like this:
Copy code
@Serializable
data class Request(
    val anonymizers: Map<String, AnonymizerType>? = null
)

@Serializable
sealed class AnonymizerType

@Serializable
@SerialName("replace")
data class Replace(
    @SerialName("new_value") val newValue: String
) : AnonymizerType()

@Serializable
@SerialName("redact")
object Redact : AnonymizerType()

// ...