我在服務器上有一個資料庫 (MySql) 和一個本地資料庫 (Room),在服務器上的資料庫中有一個名為 country 的表,在該表內有一個名為 countryName 的列,該列的型別是 JSON,如下圖所示。
圖片
countryName 里面的內容是 JSONObject
桌子
@Entity(tableName = "Countries")
public class Country {
private JSONObject countryName;
public Country(JSONObject countryName) {
this.countryName = countryName;
}
public JSONObject getCountryName() {
return countryName;
}
}
錯誤
Cannot figure out how to save this field into database. You can consider adding a type converter for it.
如何使用 Room 創建 JSONObject 列?
uj5u.com熱心網友回復:
爪哇版:
class MyConverters {
@TypeConverter
public String jsonToString(JSONObject data){
return data.toString();
}
@TypeConverter
public JSONObject stringToJson(json: JSONObject){
return JSONObject(json);
}
}
并在您的資料庫上方使用它:
@Database(entities = ....)
@TypeConverters({MyConverters.class})
public abstract class RoomDb extends RoomDatabase {
public abstract UserDao userDao();
}
uj5u.com熱心網友回復:
Room 不支持直接保存 JSON 資料型別,但是你可以寫一個 @TypeConverter
使用型別轉換器:
internal class MyConverters {
@TypeConverter
fun jsonToString(data: JSONObject): String = data.toString()
@TypeConverter
fun stringToJson(json: JSONObject): JSONObject = JSONObject(json)
}
并在您的上面使用它Dao:
@Dao
@TypeConverters(MyConverters::class)
internal abstract class MyDao
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/389622.html
標籤:爪哇 安卓 json android-room
