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.
The content inside countryName is 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?
CodePudding user response:
Room doesn't support saving JSON data type directly, but you can write a @TypeConverter
Using type converter:
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
@TypeConverters(MyConverters::class)
internal abstract class MyDao
...
CodePudding user response:
Java Version:
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();
}