【发布时间】:2020-04-15 05:49:38
【问题描述】:
在我的项目中,我遇到了一些关于在 MVVM 模式中使用 Kotlin、Retrofit 和 RxJava 返回嵌套 JSON 数据的问题。
我对 RxJava、MVVM 和 Retrofit 还比较陌生,仍然很困惑,但我想最终获得一个当前嵌套在 JSON 中的选择类别列表。
JSON 响应看起来像这样......
{
"status": "ok",
"totalResults": 38,
"articles": [
{
"source": {
"id": "business-insider",
"name": "Business Insider"
},
"author": "Hayley Peterson",
"title": "Amazon executive was killed after colliding with a van delivering the company's packages, report reveals - Business Insider",
"description": "\"I heard a scream, immediately followed by a crash,\" the van's driver testified, according to the report.",
"url": "https://www.businessinsider.com/amazons-joy-covey-killed-company-delivery-van-report-2019-12",
"urlToImage": "https://image.businessinsider.com/5e01376e855cc215577a09f1?width=1200&format=jpeg",
"publishedAt": "2019-12-23T22:32:01Z",
"content": "The former Amazon executive Joy Covey was killed after colliding with a van delivering Amazon packages, according to an explosive investigation into the company's logistics network by BuzzFeed News and ProPublica. \r\nCovey was Amazon's first chief financial of… [+1462 chars]"
},
...
我的数据类看起来像这样...
data class Base (
@SerializedName("status") val status : String,
@SerializedName("totalResults") val totalResults : Int,
@SerializedName("articles") val articles : List<Story>
)
data class Story (
@SerializedName("source") val source : Source,
@SerializedName("author") val author : String,
@SerializedName("title") val title : String,
@SerializedName("description") val description : String,
@SerializedName("url") val url : String,
@SerializedName("urlToImage") val urlToImage : String,
@SerializedName("publishedAt") val publishedAt : String,
@SerializedName("content") val content : String
)
data class Source (
@SerializedName("id") val id : String,
@SerializedName("name") val name : String
)
我首先使用我的 API 和 @GET 注释来通过这段代码获得头条新闻...
interface StoriesApi {
@GET("v2/top-headlines?country=us&apiKey=###MYKEY###")
fun getStories(): Single<List<Story>>
}
我的 StoriesService 又使用它来获取 Single>
class StoriesService {
@Inject
lateinit var api: StoriesApi
init {
DaggerApiComponent.create().inject(this)
}
fun getStories(): Single<List<Story>> {
return api.getStories()
}
}
最后,我使用下面的代码在我的 ViewModel 中调用它...
private fun fetchStories() {
loading.value = true
disposable.add(
storiesService.getStories()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object: DisposableSingleObserver<List<Story>>() {
override fun onSuccess(value: List<Story>?) {
stories.value = value
storyLoadError.value = false
loading.value = false
}
override fun onError(e: Throwable?) {
storyLoadError.value = true
loading.value = false
}
})
)
}
有什么方法可以让我只输入 JSON 的文章部分,这样我就不必对整个 JSON 响应进行过多的摆弄?我最终希望只得到一篇文章,而不是“状态”和“总结果”。
【问题讨论】:
-
你遇到了什么错误,你能提一下吗?
标签: android kotlin mvvm rx-java retrofit2