[英]Can't parse JSON response via @POST Request with parameters using Retrofit
因此,我正在尝试处理并向我的服务器打印 JSON 响应,但出现错误:
java.lang.IllegalStateException:需要一个字符串,但在第 1 行第 1376 列路径 $.scope 处为 BEGIN_ARRAY
这是我的项目的样子:
对象 RetrofitClientInstance {
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"
}
请伙计们,如果你能帮助我,我想理解
大家好,我已经找到答案了:
在我的模型类中,“范围”变量是字符串类型,但我的 JSON 返回一个数组,因此应用程序返回错误的原因。
JSON 响应返回:"scope": [ "read", "write"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.