[英]How can I create a JSONObject column using Room?
I have a database on the server (MySql) and a local database (Room), In the database on the server there is a table called countries and inside that table, There is a column called countryName and the type of that column is JSON, As you can see in the image below.我在服务器上有一个数据库(MySql)和一个本地数据库(Room),在服务器上的数据库中有一个名为国家的表,在该表内部,有一个名为 countryName 的列,该列的类型是 JSON,如下图所示。
The content inside countryName is JSONObject countryName 里面的内容是 JSONObject
The Table桌子
@Entity(tableName = "Countries")
public class Country {
private JSONObject countryName;
public Country(JSONObject countryName) {
this.countryName = countryName;
}
public JSONObject getCountryName() {
return countryName;
}
}
Error错误
Cannot figure out how to save this field into database. You can consider adding a type converter for it.
How can I create a JSONObject column using Room?如何使用 Room 创建 JSONObject 列?
Room doesn't support saving JSON data type directly, but you can write a @TypeConverter
Room 不支持直接保存 JSON 数据类型,但是可以写一个
@TypeConverter
internal class MyConverters {
@TypeConverter
fun jsonToString(data: JSONObject): String = data.toString()
@TypeConverter
fun stringToJson(json: JSONObject): JSONObject = JSONObject(json)
}
And use this above your Dao
:并在您的
Dao
上方使用它:
@Dao
@TypeConverters(MyConverters::class)
internal abstract class MyDao
...
Java Version: Java 版本:
class MyConverters {
@TypeConverter
public String jsonToString(JSONObject data){
return data.toString();
}
@TypeConverter
public JSONObject stringToJson(json: JSONObject){
return JSONObject(json);
}
}
And use this above your Database:并在您的数据库上方使用它:
@Database(entities = ....)
@TypeConverters({MyConverters.class})
public abstract class RoomDb extends RoomDatabase {
public abstract UserDao userDao();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.