由于错误,我无法在房间中创建 typeConverter。我似乎遵循文档中的所有内容。我想将列表转换为 json 字符串。让我们看看我的实体:
@Entity(tableName = TABLE_NAME)
public class CountryModel {
public static final String TABLE_NAME = "Countries";
@PrimaryKey
private int idCountry;
/* I WANT TO CONVERT THIS LIST TO A JSON STRING */
private List<CountryLang> countryLang = null;
public int getIdCountry() {
return idCountry;
}
public void setIdCountry(int idCountry) {
this.idCountry = idCountry;
}
public String getIsoCode() {
return isoCode;
}
public void setIsoCode(String isoCode) {
this.isoCode = isoCode;
}
public List<CountryLang> getCountryLang() {
return countryLang;
}
public void setCountryLang(List<CountryLang> countryLang) {
this.countryLang = countryLang;
}
}
country_lang是我想转换为字符串 json 的内容。所以我创建了以下转换器:Converters.java:
public class Converters {
@TypeConverter
public static String countryLangToJson(List<CountryLang> list) {
if(list == null)
return null;
CountryLang lang = list.get(0);
return list.isEmpty() ? null : new Gson().toJson(lang);
}}
那么问题出在我放置@TypeConverters({Converters.class}) 的任何地方,我一直收到错误消息。但正式这是我放置注释以注册 typeConverter 的地方:
@Database(entities = {CountryModel.class}, version = 1 ,exportSchema = false)
@TypeConverters({Converters.class})
public abstract class MYDatabase extends RoomDatabase {
public abstract CountriesDao countriesDao();
}
我得到的错误是:
Error:(58, 31) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.