【问题标题】:Retrofit + Moshi + Kotlin = 403 Error when trying to get Json Object尝试获取 Json 对象时改造 + Moshi + Kotlin = 403 错误
【发布时间】:2019-11-12 12:39:11
【问题描述】:

我正在尝试使用 Moshi 解析带有 Retrofit 的 JsonObject,但一直遇到 403 错误。我可以从我的浏览器访问请求,所以我很确定我在这里的设置中做错了什么..

object RetrofitFactory {
    private val moshi = Moshi.Builder()
        .add(KotlinJsonAdapterFactory())
        .build()

    fun makeRetrofitService(): Retrofit =
        Retrofit.Builder()
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .baseUrl("http://url.to.destination/")
            .build()

}

interface MyApiService {
    @GET("products.json")
    fun getPropertiesAsync(): Deferred<List<ProductProperty>>
}

object MyApi {
    val retrofitService: MyApiService by lazy {
        RetrofitFactory.makeRetrofitService().create(MyApiService::class.java)
    }
}

JsonObject (products.json) 本身以外部对象“outer”开头,如下所示:

{
  outer : [
    {inner object1},
    {inner object2},
    {inner object3}
  ]
}

但尝试获取“products.json/outer”会产生 403 错误,同时尝试获取“products.json”说: com.squareup.moshi.JsonDataException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at path $

知道我做错了什么吗?

【问题讨论】:

  • 这个错误给出了解决方案。您正在尝试访问一个数组,但它是一个对象。
  • 是的,但是有没有其他方法可以访问我在文档中没有列出的对象?
  • 试试这个fun getPropertiesAsync(): Deferred&lt;ProductProperty&gt;

标签: android retrofit2 moshi


【解决方案1】:

应该有一个具有outer 字段的类。因为outer 是一个对象。

class ProductsBody (
    @Json("outer")
    var outer: List<ProductProperty>? = null
)

interface MyApiService {
    @GET("products.json")
    fun getPropertiesAsync(): Deferred<ProductsBody> // @NOTE the change here
}


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-03
    • 2020-01-21
    • 2016-04-15
    • 1970-01-01
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    相关资源
    最近更新 更多