2

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:

  1. Treat the author as a separate entity when needed without having to pass the Book or Article objects around
  2. Avoid duplicating the Author fields

Current solutions I can think of are:

  1. Use an intermediate class like the EventJson example 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.
  2. Make the Book and Article classes subclasses of Author. 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?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.