首页 > 解决方案 > 无法通过 @POST 请求使用 Retrofit 解析 JSON 响应和参数

问题描述

因此,我正在尝试处理并向我的服务器打印 JSON 响应,但出现错误:

java.lang.IllegalStateException:应为字符串,但在第 1 行第 1376 列路径 $.scope 处为 BEGIN_ARRAY

这是我的项目的样子:

对象改造客户端实例 {

private var retrofit: Retrofit? = null
private val BASE_URL = "http://security-xxx.xxx.xxx.corp"

//create a retrofit instance, only if its not created yet
val retrofitInstance: Retrofit?
    get() {

        val okHttpClient = OkHttpClient.Builder()
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(60, TimeUnit.SECONDS)
            .connectTimeout(60, TimeUnit.SECONDS)
            .build()

        if (retrofit == null) {
            retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build()
        }
        return retrofit
    }

}

接口 GetApiService {

@GET("/xxx/token")
fun getToken(@Header("Authorization") token: String): Call<TokenResponse>

@FormUrlEncoded
@POST("/oauth/token")
fun requestTokenFromEP(
    @Field("client_id") clientId: String,
    @Field("client_secret") clientSecret: String,
    @Field("grant_type") grantType: String,
    @Field("username") username: String,
    @Field("password") password: String,
    @Field("role") role: String
) : Call<TokenResponse>

这是我的 DTO 课程

data class TokenResponse(
    @SerializedName("access_token")
    var accessToken: String,
    @SerializedName("token_type")
    var tokenType: String,
    @SerializedName("refresh_token")
    var refreshToken: String,
    @SerializedName("scope")
    var scope: String
)

我的活动

private fun doTokenRequest(){
    //get service
    val service = RetrofitClientInstance.retrofitInstance?.create(GetApiService::class.java)
    //do call
    val call = service?.requestTokenFromEP(TokenUtils.clientId, TokenUtils.clientSecret, TokenUtils.grantType,TokenUtils.username, TokenUtils.password, TokenUtils.role)
    //process it
    call?.enqueue(object : retrofit2.Callback<TokenResponse>{
        override fun onFailure(call: Call<TokenResponse>, t: Throwable) {
            println("failed: " + t.message)
        }

        override fun onResponse(call: Call<TokenResponse>, response: Response<TokenResponse>) {
            println("success")
            var myList: TokenResponse = response.body()!!
            println(myList.toString())
        }

    })

}

JSON 预期响应

{
    "access_token": "xxxxx",
    "token_type": "xxxxx",
    "refresh_token": "xxxxxxx",
    "expires_in": 553,
    "scope": "read"
}

如果你能帮助我,请大家我想了解

标签: androidjsonrestkotlinretrofit

解决方案


大家好,我已经找到答案了:

在我的模型类中,“范围”变量是字符串类型,但我的 JSON 返回一个数组,因此应用程序返回错误。

返回的 JSON 响应: "scope": [ "read", "write"]


推荐阅读