I'm working with an API that returns several JSON responses which have common data fields between them. I'm using Moshi to deserialize the responses into objects.
For example say a response from one API method call has this structure
class Book(
val title: String,
val genre: String,
...
val authorName: String,
val authorAge: Int,
val authorCountry: String
}
And another one has this structure
class Article(
val title: String,
val subject: String,
...
val authorName: String,
val authorAge: Int,
val authorCountry: String
}
I'm looking for a solution to be able to move the common fields (e.g., the author details) into a separate class and treat it as if it as if it came from a nested JSON structure, while the actual JSON received from the API is unchanged and still flat.
class Book(
val title: String,
val genre: String,
...
val author: Author
}
I want to do this so I can:
- Treat the author as a separate entity when needed without having to
pass the
BookorArticleobjects around - Avoid duplicating the
Authorfields
Current solutions I can think of are:
- Use an intermediate class like the
EventJsonexample in the Moshi docs. I want to avoid this because my data classes are quite large and I would have to duplicate all the fields in the intermediate class. - Make the
BookandArticleclasses subclasses ofAuthor. I don't like this because a Book is not an Author and because it doesn't let me treat the Author as a separate entity.
Any suggestions?