由于错误,我无法在Room中创建一个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的正确位置:
那么我的问题是任何地方我放置@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.
String
到List<CountryLang>
的转换器?我在你们的代码中没有看到它。Room也需要它来读取数据。 - yigit@TypeConverter public static List<CountryLang> jsonToCountryLang(String json)
- Gak2