【发布时间】:2019-08-15 08:10:17
【问题描述】:
我正在尝试从 github(https://github.com/JamesFT/Database-Quotes-JSON/blob/master/quotes.json) 加载 quoteJson 文件。我是改装和所有这一切的新手,所以我只是尝试遵循并理解一个教程(https://android.jlelse.eu/android-networking-in-2019-retrofit-with-kotlins-coroutines-aefe82c4d777)。如果这很愚蠢或真的很容易,非常抱歉。我仍在为此苦苦挣扎。如果我能得到一个简短的解释,为什么它会以其他方式完成,我将不胜感激!
我查看了 Retrofit 的文档,搜索了所有类似的溢出问题。问题是,如果我尝试改变
fun getQuotes(): Deferred<Response<QuoteResponse>>
到
fun getQuotes(): Deferred<ResponseList<Quotes>>
我收到一个错误
val quoteResponse = safeApiCall(...
private val okHttpClient = OkHttpClient().newBuilder()
.build()
fun retrofit() : Retrofit = Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://raw.githubusercontent.com/JamesFT/Database-Quotes-JSON/master/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(CoroutineCallAdapterFactory())
.build()
val quoteApi : QuoteApi = retrofit().create(QuoteApi::class.java)
}
型号
val quoteAuthor : String,
val quoteText : String
)
// Data Model for the Response returned from the Api
data class QuoteResponse(
val results : List<Quote>
)
//A retrofit Network Interface for the Api
interface QuoteApi{
@GET("quotes.json")
fun getQuotes(): Deferred<Response<QuoteResponse>>
// fun getQuotes(): Deferred<Response<QuoteResponse>>
}
val quoteResponse = safeApiCall(
call = {api.getQuotes().await()}, // i get the error here if i change something myself
errorMessage = "Error Fetching Popular Movies"
)
return quoteResponse?.results?.toMutableList()
}
suspend fun <T : Any> safeApiCall(call: suspend () -> Response<T>, errorMessage: String): T? {
val result : Result<T> = safeApiResult(call,errorMessage)
var data : T? = null
when(result) {
is Result.Success ->
data = result.data
is Result.Error -> {
Log.d("1.DataRepository", "$errorMessage & Exception - ${result.exception}")
}
}
return data
}
Process: com.example.quoteappmvvm, PID: 7373
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
...
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:215)```
【问题讨论】:
标签: android json kotlin gson retrofit2