Moshi and room – mapping relationships

I have that Json that I would like to map with Moshi and store with Room

{
    "name": "My Group",
    "members": [
        {
            "id": "119075",
            "invitedUser": {
                "id": 97375,
                "email": "[email protected]"
            },
            "inviting_user": {
                "id": 323915,
                "email": "[email protected]"
            }
        },
        {
            "id": "395387",
            "invitedUser": {
                "id": 323915,
                "email": "[email protected]"
            },
            "inviting_user": {
                "id": 323915,
                "email": "bbb",
            }
        }
    ]
}

I prepared my models

@Entity(tableName = "groups")
data class Group(
    @PrimaryKey
    val id: Long,
    val members: List<Member>
)

@Entity(tableName = "members")
data class Member(
    @PrimaryKey
    val id: Long,

    @Json(name = "invited_user")
    @ColumnInfo(name = "invited_user")
    val invitedUser: User,

    @Json(name = "inviting_user")
    @ColumnInfo(name = "inviting_user")
    val invitingUser: User
)

@Entity(tableName = "users")
data class User(
    @PrimaryKey
    val id: Int,

    val email: String
)

And currently, I have error: Cannot figure out how to save this field into database. I read this https://developer.android.com/training/data-storage/room/relationships. However, if I will model relationships like in documentation I don’t know how to let Moshi map the relations? Have you found the simplest solution for that problem?

Answer

You have 2 options in my opinion.

  1. You split the group and users in to individual tables and insert them separately.
  2. You use TypeConverters to store the members as a field of group.

Your implementation is going to be dependent on your use-case.