-1
嘿谷歌對使用@Relation如何保存嵌套列表<String>在RoomDB在Android
@Entity
public class Pet {
int userId;
String name;
// other fields
}
public class UserNameAndAllPets {
public int id;
public String name;
@Relation(parentColumn = "id", entityColumn = "userId")
public List<Pet> pets;
}
一個例子是可以節省字符串列表,但不爲它創建額外的類。我想避開我JsonProperty和一間實體
W之間incosistence想有soemthing像
public class UserNameAndAllPets {
@JsonProperty("id")
public int id;
@JsonProperty("name")
public String name;
@Relation(parentColumn = "id")
@JsonProperty("pets")
public List<String> pets;
}
因爲我收到以下JSON:
{
"id" : "1",
"name" : "someName",
"pets": ["cat", "dog", "camel"]
}
任何一個知道該如何解決?
編輯:
現在我的示例代碼看起來像,但我有錯誤: 錯誤:參數的類型必須與@Entity或它的集合/數組註釋的類。
@JsonIgnoreProperties(ignoreUnknown=true)
@Entity(tableName = TABLE_NAME)
public class Item {
@Ignore public static final String TABLE_NAME = "itemTable";
@PrimaryKey(autoGenerate = true)
Long id;
@JsonProperty("supplierName")
String supplierName;
@JsonProperty("eventDescription")
String eventDescription;
@JsonProperty("eventDate")
@TypeConverters(StringListToGsonConverter.class)
Date date;
@JsonProperty("carServiceType")
@TypeConverters(StringListToGsonConverter.class)
List<String> types;
public ServiceHistoryItem(Long id, String supplierName, String eventDescription, Date date, List<String> types) {
this.id = id;
this.supplierName = supplierName;
this.eventDescription = eventDescription;
this.date = date;
this.types = types;
}
public static class StringListToGsonConverter{
@TypeConverter
public static List<String> restoreList(String listOfString){
return new Gson().fromJson(listOfString, new TypeToken<List<String>>() {}.getType());
}
@TypeConverter
public static String saveListOfString(List<String> listOfString){
return new Gson().toJson(listOfString);
}
@TypeConverter
public static Date fromTimestamp(Long value) {
return value == null ? null : new Date(value);
}
@TypeConverter
public static Long dateToTimestamp(Date date) {
return date == null ? null : date.getTime();
}
}
}
EDIT2
節能項目時,爲什麼...雖然 錯誤的新問題出現 道不能插入我的實體的名單,沒有理由:該參數的類型必須是一個類註釋與@Entity或它的集合/數組。
@Dao
interface ItemDao {
@Query("SELECT * FROM " + Item.TABLE_NAME)
fun getAll(): LiveData<List<Item>>
@Query("DELETE FROM " + Item.TABLE_NAME)
fun deleteAllServiceHistory()
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertNewItem(item: Item)
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertNewItems(itemList: List<Item>) // <--- Error
}
爲道
SOLUTION如果你正在使用科特林你應該使用ArrayList
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertNewItems(itemList: ArrayList<Item>)
對於 '@TypeConverters(StringListToGsonConverter.class) 列表 SOMETYPE = NULL;' 我 *錯誤:參數的類型必須與@Entity或收集/它陣列註釋的類。* –
murt
您是否可以使用所做的更改來更新代碼? – Blackbelt
我已更新 – murt