繁体   English   中英

如何使用Retrofit2编写POJO以从JSON获取对象内部的特定数组?

[英]How to write POJOs to get specific array inside an object from JSON using Retrofit2?

好吧,我需要做一个任务:新闻分页列表。 为此,我从googlesample / architecthurecomponents / PagingWithNetworkSample中获取了一个样本,并遇到了这个问题。 问题是有关Google示例中解析JSON文件的代码。

JSON网址: https//www.reddit.com/r/androiddev/hot.json

POJO文件:

@Entity(tableName = "posts",
    indices = [Index(value = ["subreddit"], unique = false)])
data class RedditPost(
    @PrimaryKey
    @SerializedName("name")
    val name: String,
    @SerializedName("title")
    val title: String,
    @SerializedName("score")
    val score: Int,
    @SerializedName("author")
    val author: String,
    @SerializedName("subreddit") // this seems mutable but fine for a demo
    @ColumnInfo(collate = ColumnInfo.NOCASE)
    val subreddit: String,
    @SerializedName("num_comments")
    val num_comments: Int,
    @SerializedName("created_utc")
    val created: Long,
    val thumbnail: String?,
    val url: String?) {
// to be consistent w/ changing backend order, we need to keep a data like this
var indexInResponse: Int = -1
}

这是一个api接口:

interface RedditApi {
@GET("/r/{subreddit}/hot.json")
fun getTop(
        @Path("subreddit") subreddit: String,
        @Query("limit") limit: Int): Call<ListingResponse>

@GET("/r/{subreddit}/hot.json")
fun getTopAfter(
        @Path("subreddit") subreddit: String,
        @Query("after") after: String,
        @Query("limit") limit: Int): Call<ListingResponse>

@GET("/r/{subreddit}/hot.json")
fun getTopBefore(
        @Path("subreddit") subreddit: String,
        @Query("before") before: String,
        @Query("limit") limit: Int): Call<ListingResponse>

class ListingResponse(val data: ListingData)

class ListingData(
        val children: List<RedditChildrenResponse>,
        val after: String?,
        val before: String?
)

data class RedditChildrenResponse(val data: RedditPost)

companion object {
    private const val BASE_URL = "https://www.reddit.com/"
    fun create(): RedditApi = create(HttpUrl.parse(BASE_URL)!!)
    fun create(httpUrl: HttpUrl): RedditApi {
        val logger = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger {
            Log.d("API", it)
        })
        logger.level = HttpLoggingInterceptor.Level.BASIC

        val client = OkHttpClient.Builder()
                .addInterceptor(logger)
                .build()
        return Retrofit.Builder()
                .baseUrl(httpUrl)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(RedditApi::class.java)
    }
}
}

问题是:api请求如何准确找到我们所需要的东西,一个孩子:[...]代表一个帖子列表? 因为有一个子对象[...]驻留在对象内部,所以在代码中我们没有带@Serialized(“ children”)字段的POJO。 只能在儿童里面放些物品:[...]。 我尝试实现特定于json的此方法,但它返回空值。

谢谢大家的帮助。

如果POJO中的字段名称与JSON中的字段名称相同,则不必添加@SerializedName批注。 这就是为什么可以将class ListingResponse(val data: ListingData)映射到

{
  "kind": "Listing",
  "data": ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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