https://kotlinlang.org logo
#serialization
Title
# serialization
d

Davide Giuseppe Farella

03/16/2023, 9:36 PM
Hello people, I got a Json like
Copy code
[
  { // MovieRating.kt
    "rating": 7
    "movie": { // Movie.kt
      "title": ...,
      ...
  },
  { // ShowRating.kt
    "rating": 8
    "show": { // Show.kt
      "title": ...,
      ...
  }
]
For
Movie
and
Show
I've set the discriminator as:
Copy code
@SerialName("movie")
data class Movie(...): Parent
Now, how to properly set a discriminator for
MovieRating
and
ShowRating
, based on the inner field
"movie"
/
"show"
?
1
e

ephemient

03/16/2023, 9:52 PM
it will be easier to deserialize to a
Copy code
@Serializable
data class RatingContainer(
    val rating: Int,
    movie: MovieRating? = null,
    show: ShowRating? = null,
)
and then map that to the structure you want, possibly wrapped up with https://github.com/Kotlin/kotlinx.serialization/blob/master/docs/serializers.md#composite-serializer-via-surrogate
d

Davide Giuseppe Farella

03/16/2023, 10:08 PM
Thank you for your answer! I would be glad if I could achieve that without a middle class, as I already have many classes for Trakt API and it’s getting confusing 😄 I will take a look at that doc. Have you got any alternatives? I rather create a custom serializer, than another data structure 🙂
I took some time to understand the doc: so, basically, the container you mentioned will be used only by the serializer and it will not be part of my model's hierarchy. That sounds amazing! I will give it a try tomorrow. Thank you again.
Awesome 🍻
2 Views