Search code examples
androidkotlintypesormandroid-room

How to write to db with room framework


How to write to data base such structure with room?

{
    "Status": 200,
    "Result": {
        "10": {
            "name": "test1",
            "surname": "test2"
        },
        "2": {
            "name": "tets",
            "surname": "test2"
        }
    }
}

but I need create an object from structure as:

val int id; //example 10
val name;
val surname;

Solution

  • Your JSON structure cannot be directly translated to Room, as Room doesn't support dynamic keys. Instead, represent data with a "User" entity in Room and an "ApiResponse" data class. Like this:

    @Entity(tableName = "user")
    data class User(@PrimaryKey val id: Int, val name: String, val surname: String)
    
    data class ApiResponse(val Status: Int, val Result: Map<String, User>)
    

    Setup your DAO and Room DB:

    @Dao
    interface UserDao {
        @Query("SELECT * FROM user") fun getAll(): List<User>
        @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAll(users: List<User>)
    }
    
    @Database(entities = [User::class], version = 1)
    abstract class AppDatabase : RoomDatabase() {
        abstract fun userDao(): UserDao
    }
    

    After receiving your JSON response, parse it into ApiResponse, convert Result into a list of User objects, and save them:

    val apiResponse = Gson().fromJson(jsonString, ApiResponse::class.java)
    val users = apiResponse.Result.values.toList()
    AppDatabase.getDatabase(context).userDao().insertAll(users)
    

    Your JSON must include "id" in each user object. Adjust your JSON or parsing logic as needed.