Android room persistent library - how to insert class that has a List object field

You can easly insert the class with list object field using TypeConverter and GSON,

public class DataConverter {

    @TypeConverter
    public String fromCountryLangList(List<CountryLang> countryLang) {
        if (countryLang == null) {
            return (null);
        }
        Gson gson = new Gson();
        Type type = new TypeToken<List<CountryLang>>() {}.getType();
        String json = gson.toJson(countryLang, type);
        return json;
    }

    @TypeConverter
    public List<CountryLang> toCountryLangList(String countryLangString) {
        if (countryLangString == null) {
            return (null);
        }
        Gson gson = new Gson();
        Type type = new TypeToken<List<CountryLang>>() {}.getType();
        List<CountryLang> countryLangList = gson.fromJson(countryLangString, type);
        return countryLangList;
    }
 }

Next, Add the @TypeConverters annotation to the AppDatabase class

    @Database(entities = {CountryModel.class}, version = 1)
    @TypeConverters({DataConverter.class})
    public abstract class AppDatabase extends RoomDatabase {
      public abstract CountriesDao countriesDao();
    }

For more information about TypeConverters in Room check our blog here and the official docs.


Here is the Aman Gupta's converter in Kotlin for lazy Googler's who enjoy copy pasting:

class DataConverter {

    @TypeConverter
    fun fromCountryLangList(value: List<CountryLang>): String {
        val gson = Gson()
        val type = object : TypeToken<List<CountryLang>>() {}.type
        return gson.toJson(value, type)
    }

    @TypeConverter
    fun toCountryLangList(value: String): List<CountryLang> {
        val gson = Gson()
        val type = object : TypeToken<List<CountryLang>>() {}.type
        return gson.fromJson(value, type)
    }
}

Also, add the @TypeConverters annotation to the AppDatabase class

@Database(entities = arrayOf(CountryModel::class), version = 1)
@TypeConverters(DataConverter::class)
abstract class AppDatabase : RoomDatabase(){
    abstract fun countriesDao(): CountriesDao
}