I'm using moshi with codegen. I have a class `User...
# squarelibraries
I'm using moshi with codegen. I have a class
with many fields and class
which should have all the fields from
plus some other keys. That's how I'm receiving it from the server:
just has some additional fields that should be presented in json. e.g. user is
{"name":"Phil", "avatarUrl":"<https://some.url>"}
and current user is
{"name":"Phil", "avatarUrl":"<https://some.url>", "token":"lorem ipsum"}
I could've inherit, but it'd require me to repeat all of user fields. I solved it by making a custom adapter factory that reads extra properties from json and than pass it to
to fill it. But it takes a lot of boilerplate code, maybe there's some built in solution for such case? I'd like to add some annotation to
property so codegen would write something similar for me. Or is there a way to build a general factory for such cases?
Copy code
data class CurrentUser(
    val token: String,
    val user: User,
) {
    companion object {
        private const val tokenKey = "token"

        val adapterFactory = JsonAdapter.Factory { type, _, moshi ->
            if (type != CurrentUser::class.java) {
                return@Factory null

            val userJsonAdapter = moshi.adapter(User::class.java)
            object : JsonAdapter<CurrentUser>() {
                override fun fromJson(reader: JsonReader): CurrentUser? {
                    val jsonValue = reader.readJsonValue()
                        ?: return null
                    if (jsonValue !is Map<*, *>) {
                        throw IllegalStateException("${this@Companion} readJsonValue is not map: $jsonValue")
                    return CurrentUser(
                        token = jsonValue[tokenKey] as? String
                            ?: throw IllegalStateException("$tokenKey not found in $jsonValue"),
                        user = userJsonAdapter.fromJsonValue(jsonValue)
                            ?: throw IllegalStateException("Failed to parse user from $jsonValue"),

                override fun toJson(writer: JsonWriter, value: CurrentUser?) {
                        ?.plus(mapOf(tokenKey to value.token))
Zac def knows better than I and I'm still not an amazing software engineer, but if this were me I think I would just treat that "DTO" object as always being
and then in my domain or something, I would just check if
exists (or some other invariant) and then map to a different domain model (
) based on that invariant. Seems dead simple to me that way (which is nice?)
@Zac Sweers the issues seems to be relevant, but it doesn't seems to be resolved to me, and I didn't get how the sample from the comment can help. So the problem is to read a flat json - not
into some object which will be a composition of other objects.
@Colton Idle I guess that's an option, but it still requires a lot of properties duplication when mapping to the domain model
I guess from Kotlin perspective perfectly both user and current user should be interfaces, and code generation would build classes based on inherited properties. But I don't think Moshi can do something like this.
If at the root of your object you had a
field then you could use PolymorphicTypeAdapter from moshi to go into a User or CurrentUser pretty easily (if I'm understanding the question correctly).
Maybe you can use PTA to have a discriminator based on the presence of a field in json...?