简体   繁体   中英

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.

The Image

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?

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
...

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();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM