Nested json data store in room database, where data is in form of arraylist. So how to get data which are inside array of object of object for insert into table
here is json { "kind": "books#volumes", "totalItems": 1, "items": [ { "kind": "books#volume", "id": "U4onjgEACAAJ", "etag": "UpSu6n ogwU", "selfLink": "https://www.googleapis.com/books/v1/volumes/U4onjgEACAAJ", "volumeInfo": { "title": "Home", "authors": [ "Carson Ellis" ], "publishedDate": "2016-06-01", "pageCount": 40, "printType": "BOOK", "imageLinks": { "smallThumbnail": "http://books.google.com/books/content?id=U4onjgEACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api", "thumbnail": "http://books.google.com/books/content?id=U4onjgEACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api" }, "language": "en" } } ] }
here is my Data Model class from where i get volume info
data class BookData(
val items: List<Item>
)
data class Item(
val id: String,
val volumeInfo: VolumeInfo
)
@Entity
data class VolumeInfo(
@PrimaryKey(autoGenerate = false)
val id:Int,
val publishedDate: String,
val publisher: String,
val title: String
)
problem is in repository how do i store VolumeInfo.
repository class
class BookRepository @Inject constructor(private val bookAPI: BookAPI,
private val bookDatabase: BookDatabase
){
private val book_data = MutableLiveData<BookData>()
val live_book_data: LiveData<BookData>
get() = book_data
suspend fun getBookLists(q:String){
val results = bookAPI.getBookList(q)
if (results.isSuccessful && results.body() != null){
bookDatabase.getBookDAO().addBookList(results.body()!!.items)
book_data.postValue(results.body())
}else{
Log.d("Retrofit response", "response fail")
}
}
}
CodePudding user response:
It seems to me that you actually want your @Entity
(i.e. database table) to be BookData
, not VolumeInfo
. Item and VolumeInfo are embedded fields. Or perhaps you want separate tables for all three data classes? Regardless, you'll need to use other annotations, like @PrimaryKey
, @Embedded
, and @Relation
to define various relationships between fields in your data class hierarchy.
You'll find it very helpful to read up on relationships in Room. Check out Define relationships between objects for more help.