问题描述
我有一个带有Android应用程序的项目,可从wordpress rest api获取帖子 我需要的某些字段就是此列表。
[
{
"id": 43600,"date": "2020-09-07T19:52:47","title": {
"rendered": "Video: .... "
},"content": {
"rendered": "<div class=\"wp-block-embed__wrapper\"></div>","protected": false
},"author": 31,"featured_media": 43601,"categories": [
788,2760
]
}
]
已经阅读:
https://developer.android.com/training/data-storage/room
How to parse data of WordPress REST API using Retrofit and GSON?
Wordpress API - How to loop through a JSON Array of objects in Android/Java
Android Kotlin parsing nested JSON
Parse Json to Primative Array Kotlin
最接近的答案,但主要是在转换器中
Android Room Database: How to handle Arraylist in an Entity?
https://medium.com/@gilesjeremydev/room-through-a-complete-example-ce5c9ed417ba
我试图将其保存到具有单个实体空间的本地存储中。但是基于google doc,它将分成2个与注解@relation关联的实体
@Entity(tableName = "post")
data class SomePost(
@PrimaryKey
@field:Serializedname("id")
val id: Int,@field:Serializedname("date")
val date: String,@Embedded
@field:Serializedname("title")
val title: PostTitle,@Embedded
@field:Serializedname("content")
val content: PostContent,@field:Serializedname("featured_media")
val imageId: Int,@field:Serializedname("author")
val author: Int
)
@Entity
data class PostCategories(
@PrimaryKey(autoGenerate = true)
val id: Int,@field:Serializedname("categories")
val postCategories: Int
)
data class SomePostRelationship (
@Embedded
var post: SomePost? = null,@Relation(
parentColumn = "id",entityColumn = "categories"
)
var categories: List<PostCategories>? = null
)
interface PostService {
companion object {
const val ENDPOINT = "https://example.com/wp-json/"
}
// Posts
@GET("wp/v2/posts/")
suspend fun getPostAll(
@Query("page") page: Int? = null,@Query("per_page") perPage: Int? = null,@Query("search") search: String? = null,@Query("order") order: String? = null
): Response<List<somePost>>
问题是数据类PostCategories。
我的问题是如何将json数组序列化为Android房间类别的实体数据类。
如果已经有答案或希望有相同的问题可以链接到它。
解决方法
尝试了一些变化之后。
我决定现在使用转换器并将其组合到数据类中。
@Entity(tableName = "post")
data class SomePost(
...
@field:SerializedName("categories")
var categories: ArrayList<Int>? = null,...
)
class Converters {
...
@TypeConverter
fun listToInt(value: ArrayList<Int>?): String? {
return Gson().toJson(value)
}
@TypeConverter
fun intToList(value: String?): ArrayList<Int>? {
val type = object : TypeToken<ArrayList<Int>?>() {}.type
return Gson().fromJson(value,type)
}
}